项目需求
在做一个项目时需要有这样的功能:用户可以通过微信小程序录音且录音完成后可以播放自己的录音。
项目实施
首先,在前端界面上绘制几个按钮,分别添加上点击事件。
index.wxml
<!--index.wxml--><view class="container"><button type="primary" bindtap="start">开始录音</button><button type="primary" bindtap="suspend">录音暂停</button><button type="primary" bindtap="continue">继续录音</button><button type="primary" bindtap="stop">录音停止</button><button type="primary" bindtap="play">播放录音</button></view>
index.wxss
/**index.wxss**/button {margin: 20rpx;font-size: 30rpx;}
效果如下图所示:
然后,在js文件里完成页面需要的点击事件。注意,这里的录音管理器是RecorderManager。
onLoad: function (options) {var that = this;//获取全局唯一的录音管理器 RecorderManager实例that.recorderManager = wx.getRecorderManager()that.recorderManager.onStop((res) => {that.setData({tempFilePath: res.tempFilePath // 文件临时路径})console.log('获取到文件:' + that.data.tempFilePath)})this.recorderManager.onError((res) => {console.log('录音失败了!')//console.log(res)})},
开始录音的事件可以设置一些参数,如:采样率、录音通道数、音频格式等。
//开始录音start: function () {this.recorderManager.start({duration: 60000,sampleRate: 16000, //采样率,有效值 8000/16000/44100numberOfChannels: 1, //录音通道数,有效值 1/2encodeBitRate: 96000, //编码码率format: 'mp3', //音频格式,有效值 aac/mp3frameSize: 50, //指定帧大小audioSource: 'auto' //指定录音的音频输入源,可通过 wx.getAvailableAudioSources() 获取})},
录音暂停、继续录音、录音停止事件只需要调用微信小程序的API即可。
//录音暂停suspend: function () {this.recorderManager.pause()},//继续录音continue: function () {this.recorderManager.resume()},//录音停止stop: function () {this.recorderManager.stop()},
播放录音事件需要先获取 innerAudioContext 实例,然后设置音频文件的路径,调用 onPlay() 方法即可播放。
//播放录音play: function () {// 获取innerAudioContext实例const innerAudioContext = wx.createInnerAudioContext()// 是否自动播放innerAudioContext.autoplay = true// 设置音频文件的路径innerAudioContext.src = this.data.tempFilePath;// 播放音频文件innerAudioContext.onPlay(() => {console.log('开始播放')});// 监听音频播放错误事件innerAudioContext.onError((res) => {console.log(res.errMsg)console.log(res.errCode)})}})
注意事项
之前播放音频使用的微信小程序接口是wx.playVoice(Object object)
,但是从基础库 1.6.0 开始,该接口停止维护,所以我们使用 wx.createInnerAudioContext 代替。
完整项目代码获取:》》传送门《《