翻阅不少资料都发现小程序对wx.startRecord()接口不在维护,
注意:1.6.0 版本开始,本接口不再维护。建议使用能力更强的 wx.getRecorderManager 接口
需要使用新的接口来处理,官方文档又不符合我的需求,所以就决定自己动手来实现一下录音播放功能。
因此我们使用的使用 wx.getRecorderManager 接口:
首先使用方法获取对象
const recorderManager = wx.getRecorderManager() const innerAudioContext = wx.createInnerAudioContext()
然后写一个button来调用开始录音的方法。
//开始录音的时候 start: function () { 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); }) },
再写一个button来调用停止录音的方法。
//停止录音 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) }) },
这样就完成新API的操作了,WXML代码如下:
<button bindtap="start" class='btn'>开始录音</button> <button bindtap="stop" class='btn'>停止录音</button> <button bindtap="play" class='btn'>播放录音</button>
但是我发现点击播放根本播放不出来。这是为什么呢,路径也可以打印出来,原来小程序返回的临时路径根本无法播放,
需要通过wx.uploadFile()方法来从后台获取处理好的mp3文件来进行播放。
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: "网络请求失败,请确保网络是否正常", 36. showCancel: false, 37. success: function (res) { 38. } 39. }); 40. wx.hideToast(); 41. } 42. });
实现完成后的小程序部分截图如下:将onStop中获取到的临时路径上传到你的服务器当中,进行处理语音识别和语义,将返回的结果放到audio播放组件中就可以播放音频了。
深蓝互联成立于2013年,是一家物联网硬件开发及软件应用服务商,获得多次获得国家高新技术企业资质的企业。深蓝互联专注软硬件技术开发的专业性技术公司。我们从事软硬件开发十年,擅长SaaS 平台开发、APP小程序开发、软硬件结合开发,在视觉识别处理、数据架构、云计算、多线程高并发和集群、数据安全加密和防护方便有很深的技术积累。
我们拥有专业优秀的设计和技术团队,以极具创意的 UI 设计、精湛卓越的开发技术,专业的网络策划团队。公司多年来投入打造物联网SaaS平台,集成了公司研发的多款智能物联网终端(智能鲜米机、生鲜售货机、自助洗车机、小区电瓶车充电系统等)。
公司一直坚持以研发为导向,打造软硬件结合的物联网平台系统。将一直坚持提高开发的技术实力更好的为我们的客户服务!
文章来自深蓝互联http://www.szdbi.com/WEBkaifajishu/303.html转载请注明出处!