微信小程序錄音


wx.getUserInfo(object)

在微信小程序的官方文檔中有提出,此接口有調整,使用該接口將不再出現授權彈窗,請使用<button open-type=”getUserInfo”></button>引導用戶主動進行授權,我把授權放在了用戶第一次操作的按鈕上。

在用戶第一次登陸的時候,渲染授權按鈕。當storage中已經存有openid的時候,渲染錄音按鈕

<!-- 用戶授權按鈕 -->
<button class='mike' wx:if="{{userInfo}}" hover-class='curStyle' open-type='getUserInfo' bindgetuserinfo='login'></button>
<!-- 錄音按鈕 -->
<button class='mike' wx:if="{{record}}" hover-class='curStyle' bindtouchstart='startHandel' bindtouchend='endHandle'></button> 

交互邏輯:當用戶按下按鈕時,顯示loading提示框(開始錄音),松開時,隱藏loading並開始正在努力搜索的提示框,上傳錄制的音頻成功,跳轉到搜索結果頁。

綁定的事件:bindtouchstart(手指觸摸動作開始)和bindtouchend(手指觸摸動作結束)。當組件觸發事件時,會收到一個事件對象,其中有timeStamp,事件生成時的事件戳。兩個事件分別記錄開始錄音時間startTime和結束錄音時間endTime,因為用戶不知道長按錄音還是僅點擊開始錄音,當用戶短按的時候即endTime - startTime<350時,提示說話時間太短,來引導長按才是開始錄音

錄音管理器getRecorderManager

用到getRecorderManager的start開始錄音方法和stop停止錄音方法,比較坑的是用到start方法時,第一次錄音的用戶會自動彈出要使用你的錄音功能,是否允許?這樣會影響到識別松開按鈕這個動作,所以我用一個recordStatus錄音授權的狀態來控制。

當recordStatus為false時,只向用戶發起錄音的請求,而不做其他的操作

當recordStatus為true時,按下按鈕開始錄音,松開按鈕正在努力搜索......

//按下按鈕
    startHandel: function (e) { var that = this; var startTime = e.timeStamp; var recordStatus = that.data.recordStatus; if (!recordStatus){ wx.getSetting({ success(res) { if (!res.authSetting['scope.record']) { wx.authorize({ scope: 'scope.record', success() { recordStatus=true; that.setData({ recordStatus: recordStatus }) } }) } } }) }else{ //記錄開始錄音時間
 that.setData({ startTime: startTime }) wx.showLoading({ title: '開始錄音', mask: true }) recorderManager.onStart(() => { console.log('recorder start') }) const options = { duration: 10000, sampleRate: 44100, numberOfChannels: 1, encodeBitRate: 96000, format: 'mp3', frameSize: 50 } recorderManager.start(options); } }, //松開按鈕
    endHandle: function (e) { var that = this; var recordStatus = that.data.recordStatus; console.log(recordStatus); if (recordStatus){ var endTime = e.timeStamp; var speakTime = endTime-that.data.startTime; //如果錄音時間太短,提示
                if (speakTime < 350 ){ wx.showToast({ title: '說話時間太短', icon: 'none', }) recorderManager.stop(); }else{ wx.hideLoading(); wx.showToast({ title: '正在努力搜索', icon: 'loading', duration: 6000, mask: true }) recorderManager.onStop((res) => { const { tempFilePath } = res; //上傳錄制的音頻
                                  wx.uploadFile({                                                                   url:'https://cookbook.cityshop.com.cn/index.php?r=product/tune', filePath: tempFilePath, name: 'viceo', success: function (res) { wx.hideToast(); //如果為空
                                          if (res.statusCode!=500){ that.wxSearchAddHisKey(res.data); } if (speakTime >= 350){ wx.navigateTo({ url: '../result/result?searchValue=' + res.data }) } } }) }) //觸發錄音停止
 recorderManager.stop(); } } },

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM