在微信小程序里面里面使用录音的功能,首先判读设备是否有录音的权限。
wx.getSetting({ success(res) { if (res.authSetting['scope.record']) { _this.setData({ mkf: '麦克风权限已启用' }) } else { wx.authorize({ scope: 'scope.record', success() { // 用户已经同意小程序使用录音功能,后续调用 wx.startRecord 接口不会弹窗询问 // wx.startRecord() _this.setData({ mkf: '麦克风权限已启用' }) } })} } })
获取全局唯一的录音管理器,然后录音都依赖他,而播放录音则需要内部 audio 上下文 innerAudioContext 对象。
const recorderManager = wx.getRecorderManager()const innerAudioContext = wx.createInnerAudioContext()var tempFilePath;录音的属性配置
const options = { duration: 600000,//指定录音的时长,单位 ms sampleRate: 16000,//采样率 numberOfChannels: 1,//录音通道数 encodeBitRate: 96000,//编码码率 format: 'mp3',//音频格式,有效值 aac/mp3 frameSize: 50,//指定帧大小,单位 KB }开始录音
recorderManager.start(options); recorderManager.onStart(() = { console.log('recorder start') });停止录音 拿到录音文件
stop: function () { recorderManager.stop(); recorderManager.onStop((res) = { this.tempFilePath = res.tempFilePath; console.log('停止录音', res.tempFilePath) const { tempFilePath } = res }) },播放录音(ps:在暂停录音的时候,记录下当前暂停的时间,然后使用seek()方法,跳到当前时间播放)
innerAudioContext.src = this.tempFilePath, innerAudioContext.seek(this.data.playRecord) innerAudioContext.play()暂停录音
innerAudioContext.pause()