<button bindtap="start" class='btn'>开始录音</button>
<button bindtap="pause" class='btn'>暂停录音</button>
<button bindtap="resume" class='btn'>继续录音</button>
<button bindtap="stop" class='btn'>停止录音</button>
<button bindtap="play" class='btn'>播放录音</button>
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()
Page({
data: {
},
onLoad: function () {
},
//开始录音的时候
start: function () {
var that=this
const options = {
duration: 10000,//指定录音的时长,单位 ms
sampleRate: 16000,//采样率
numberOfChannels: 1,//录音通道数
encodeBitRate: 96000,//编码码率
format: 'mp3',//音频格式,有效值 aac/mp3
frameSize: 50,//指定帧大小,单位 KB
}
//开始录音
wx.authorize({
scope: 'scope.record',
success() {
console.log("录音授权成功");
//第一次成功授权后 状态切换为2
that.setData({
status: 2,
})
recorderManager.start(options);
recorderManager.onStart(() => {
console.log('recorder start')
});
//错误回调
recorderManager.onError((res) => {
console.log(res);
})
},
fail() {
console.log("第一次录音授权失败");
wx.showModal({
title: '提示',
content: '您未授权录音,功能将无法使用',
showCancel: true,
confirmText: "授权",
confirmColor: "#52a2d8",
success: function (res) {
if (res.confirm) {
//确认则打开设置页面(重点)
wx.openSetting({
success: (res) => {
console.log(res.authSetting);
if (!res.authSetting['scope.record']) {
//未设置录音授权
console.log("未设置录音授权");
wx.showModal({
title: '提示',
content: '您未授权录音,功能将无法使用',
showCancel: false,
success: function (res) {
},
})
} else {
//第二次才成功授权
console.log("设置录音授权成功");
that.setData({
status: 2,
})
recorderManager.start(options);
recorderManager.onStart(() => {
console.log('recorder start')
});
//错误回调
recorderManager.onError((res) => {
console.log(res);
})
}
},
fail: function () {
console.log("授权设置录音失败");
}
})
} else if (res.cancel) {
console.log("cancel");
}
},
fail: function () {
console.log("openfail");
}
})
}
})
},
//暂停录音
pause: function () {
recorderManager.pause();
recorderManager.onPause((res) => {
console.log('暂停录音')
})
},
//继续录音
resume: function () {
recorderManager.resume();
recorderManager.onStart(() => {
console.log('重新开始录音')
});
//错误回调
recorderManager.onError((res) => {
console.log(res);
})
},
//停止录音
stop: function () {
recorderManager.stop();
recorderManager.onStop((res) => {
this.tempFilePath = res.tempFilePath;
console.log('停止录音', res.tempFilePath)
const { tempFilePath } = res
})
},
//播放声音
play: function () {
innerAudioContext.autoplay = true
innerAudioContext.src = this.tempFilePath,
innerAudioContext.onPlay(() => {
console.log('开始播放')
})
innerAudioContext.onError((res) => {
console.log(res.errMsg)
console.log(res.errCode)
})
},
})