微信小程序录音器recorderManager
简单使用
1.使用wxml
<view class="btn" bindtap="start" wx:if="{{isStart==0}}">开始录音 </view>
<view class="btn" bindtap="end" wx:if="{{isStart==1}}">结束录音 ({{count}})</view>
2.定义 js
let recorderManager = null
const recorderManagerOptions = {
duration: 10000,//指定录音的时长,单位 ms
sampleRate: 16000,//采样率
numberOfChannels: 1,//录音通道数
encodeBitRate: 96000,//编码码率
format: 'mp3',//音频格式,有效值 aac/mp3
frameSize: 50,//指定帧大小,单位 KB
}
let timer2 = null
Page({
data: {
count: 30,
startTimestamp: 0,
isStart:0,
tempFilePath:''
},
onLoad: {
this.inItRecord()
},
inItRecord() {
recorderManager = wx.getRecorderManager()
recorderManager.onStart(() => {
console.log('录音开始...')
})
recorderManager.onError((res) => {
clearInterval(timer2);
wx.showToast({ title: '录音失败,请重试', icon: 'none' })
this.setData({ count: 30, isStart: 0 })
})
recorderManager.onStop((res) => {
console.log('录音结束')
if (this.data.isBack) return
if ((Date.now() - this.data.startTimestamp) / 1000 < 5) {
wx.showToast({title: '录音时间太短,请重新录音!', icon: 'none', duration: 1500})
this.setData({ count: 30 })
return
}
const { tempFilePath } = res
this.setData({ tempFilePath }, () => {
this.upload(tempFilePath)
})
})
recorderManager.onFrameRecorded((res) => {
const { frameBuffer } = res
console.log('frameBuffer.byteLength', frameBuffer.byteLength)
})
},
onUnload() {
clearInterval(timer2)
timer2 = null
},
countDown() {
timer2 = setInterval(() => {
let num = this.data.count
num--
this.setData({ count: num })
if (num <= 0) {
clearInterval(this.data.timer);
recorderManager.stop()
}
}, 1000);
},
async start() {
let res = await app.getRecordLimit()
if (res === 200) {
recorderManager.start(recorderManagerOptions);
this.data.startTimestamp = Date.now();
this.countDown();
this.setData({ isStart: 1 })
}
},
end() {
clearInterval(timer2)
timer2 = null
recorderManager.stop()
that.setData({ isStart: 0 })
},
upload() {
let that = this
wx.uploadFile({
filePath: that.data.tempFilePath,
name: 'file',
url: that.data.baseUrl + '/api/common/upload',
formData: { },
success(res) {
console.log(res);
},
fail(err) {
console.log(err);
}
})
},
3.录音权限
getRecordLimit() {
return new Promise((resolve, reject) => {
wx.getSetting({
success(res) {
// 未授权
if (!res.authSetting['scope.record']) {
wx.authorize({
scope: 'scope.record',
success() {
resolve(200)
},
fail(err) {
wx.showModal({
title: '温馨提示',
content: '请确认授权麦克风',
showCancel: true,
confirmText: "授权",
success: function (res) {
if (res.confirm) {
wx.openSetting({
success: (res) => {
if (!res.authSetting['scope.record']) {
wx.showModal({
title: '提示',
content: '您未授权录音,功能将无法使用',
showCancel: false,
success: function () { }
})
} else {
resolve(200)
}
},
fail: function () {
console.log("授权设置录音失败");
}
})
}
},
fail: function (err) {
console.log("打开录音弹框失败 => ", err);
}
})
}
})
} else {
resolve(200)
}
}
})
})
},