以录音功能为例记录一下微信小程序中授权的过程。
wxml:定义三个方法
<view>
<button bindtap='record'>开始录音</button>
<button bindtap='stop'>停止录音</button>
<button bindtap='play'>播放录音</button>
</view>
js:
在文件顶部定义
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()
data: {
tempFilePath:""
},
record(){
var that = this;
wx.getSetting({
success(res){
if (res.authSetting['scope.record']){
wx.showToast({
title: '开始录音',
icon: 'success',
duration: 1000
})
that.start();
} else {
wx.authorize({
scope: 'scope.record',
success: function(){
that.start()
},
fail:function(){
wx.showModal({
title: '提示',
content: '无法使用录音功能',
confirmText:"是"
})
}
})
}
},
fail:function(){
}
})
},
start(){
const options = {
duration: 10000,//指定录音的时长,单位 ms
sampleRate: 16000,//采样率
numberOfChannels: 1,//录音通道数
encodeBitRate: 96000,//编码码率
format: 'mp3',//音频格式,有效值 aac/mp3
frameSize: 50,//指定帧大小,单位 KB
}
recorderManager.start(options);
recorderManager.onStart(() => {
console.log('recorder start')
});
//错误回调
recorderManager.onError((res) => {
console.log(res);
})
},
stop(){
recorderManager.stop();
recorderManager.onStop((res) => {
this.tempFilePath = res.tempFilePath;
console.log('停止录音', res.tempFilePath)
const { tempFilePath } = res
})
},
play(){
innerAudioContext.autoplay = true
innerAudioContext.src = this.tempFilePath,
innerAudioContext.onPlay(() => {
console.log('开始播放')
})
innerAudioContext.onError((res) => {
console.log(res.errMsg)
console.log(res.errCode)
})
},