翻閱不少資料都發(fā)現(xiàn)小程序?qū)?/strong>wx.startRecord()接口不在維護(hù),
注意:1.6.0 版本開始,本接口不再維護(hù)。建議使用能力更強(qiáng)的 wx.getRecorderManager 接口
需要使用新的接口來處理,官方文檔又不符合我的需求,所以就決定自己動(dòng)手來實(shí)現(xiàn)一下錄音播放功能。
因此我們使用的使用 wx.getRecorderManager 接口:
首先使用方法獲取對(duì)象
const recorderManager = wx.getRecorderManager() const innerAudioContext = wx.createInnerAudioContext()
然后寫一個(gè)button來調(diào)用開始錄音的方法。
//開始錄音的時(shí)候
start: function () {
const options = {
duration: 10000,//指定錄音的時(shí)長(zhǎng),單位 ms
sampleRate: 16000,//采樣率
numberOfChannels: 1,//錄音通道數(shù)
encodeBitRate: 96000,//編碼碼率
format: 'mp3',//音頻格式,有效值 aac/mp3
frameSize: 50,//指定幀大小,單位 KB
}
//開始錄音
recorderManager.start(options);
recorderManager.onStart(() => {
console.log('recorder start')
});
//錯(cuò)誤回調(diào)
recorderManager.onError((res) => {
console.log(res);
})
},
再寫一個(gè)button來調(diào)用停止錄音的方法。
//停止錄音
stop: function () {
recorderManager.stop();
recorderManager.onStop((res) => {
this.tempFilePath = res.tempFilePath;
console.log('停止錄音', res.tempFilePath)
const { tempFilePath } = res
})
},
最后寫一個(gè)播放聲音的方法
//播放聲音
play: function () {
innerAudioContext.autoplay = true
innerAudioContext.src = this.tempFilePath,
innerAudioContext.onPlay(() => {
console.log('開始播放')
})
innerAudioContext.onError((res) => {
console.log(res.errMsg)
console.log(res.errCode)
})
},
這樣就完成新API的操作了,WXML代碼如下:
<button bindtap="start" class='btn'>開始錄音</button> <button bindtap="stop" class='btn'>停止錄音</button> <button bindtap="play" class='btn'>播放錄音</button>
但是我發(fā)現(xiàn)點(diǎn)擊播放根本播放不出來。這是為什么呢,路徑也可以打印出來,原來小程序返回的臨時(shí)路徑根本無法播放,
需要通過wx.uploadFile()方法來從后臺(tái)獲取處理好的mp3文件來進(jìn)行播放。
1. setTimeout(function () {
2. var urls = app.globalData.urls + "/Web/UpVoice";
3. console.log(s.data.recodePath);
4. wx.uploadFile({
5. url: urls,
6. filePath: s.data.recodePath,
7. name: 'file',
8. header: {
9. 'content-type': 'multipart/form-data'
10. },
11. success: function (res) {
12. var str = res.data;
13. var data = JSON.parse(str);
14. if (data.states == 1) {
15. var cEditData = s.data.editData;
16. cEditData.recodeIdentity = data.identitys;
17. s.setData({ editData: cEditData });
18. }
19. else {
20. wx.showModal({
21. title: '提示',
22. content: data.message,
23. showCancel: false,
24. success: function (res) {
25.
26. }
27. });
28. }
29. wx.hideToast();
30. },
31. fail: function (res) {
32. console.log(res);
33. wx.showModal({
34. title: '提示',
35. content: "網(wǎng)絡(luò)請(qǐng)求失敗,請(qǐng)確保網(wǎng)絡(luò)是否正常",
36. showCancel: false,
37. success: function (res) {
38. }
39. });
40. wx.hideToast();
41. }
42. });
實(shí)現(xiàn)完成后的小程序部分截圖如下:將onStop中獲取到的臨時(shí)路徑上傳到你的服務(wù)器當(dāng)中,進(jìn)行處理語(yǔ)音識(shí)別和語(yǔ)義,將返回的結(jié)果放到audio播放組件中就可以播放音頻了。
