1.template文本,提供一個按住錄制的按鈕
<view class="tip-touchmove" wx:if="{{showCancelType==2}}">
上滑取消
</view>
<view class="tip-touchmove" wx:if="{{showCancelType==3}}">
松開手指,取消錄音
</view>
<view class="voice-tool" catch:touchend="onTouchEnd" bind:touchstart="onTouchStart" bind:longpress="onLongpress" catch:touchmove="onTouchMove"> <view class="tool-text">按住說話錄音</view> </view>
2.script文本,
recordInit---錄音權限是否開啟
duration---錄音的有效時長
onTouchStart(e) { this.$apply(); if (!this.recordInit) { this.judgeRecord(); return false; } }, onLongpress(e) { if (!this.recordInit) { return false; }
//在這里處理錄音開始之后頁面上的顯示效果
this.$apply(); const RecorderManager = wx.getRecorderManager(); RecorderManager.onStart((res) => { console.log('開始錄音了') this.recording = true; this.startTime = new Date().getTime(); this.vInterval = setInterval(()=>{ let duration = (new Date().getTime() - this.startTime)/1000;//秒 this.duration = parseInt(duration) + '′' + parseInt((parseFloat(duration) - parseInt(duration)) * 100) + "″"; this.widthPersent = ((duration/60)*100) + '%'; this.$apply(); }, 60); this.$apply(); }) RecorderManager.onStop((res) => { console.log('結束錄音了', res); //這里處理錄音結束之后的顯示效果this.$apply(); if (this.showCancelType == 3) { this.duration= '00′00″'; this.startTime= ''; this.widthPersent= '0%'; this.showCancelType = 1; clearInterval(this.vInterval) this.$apply(); }else { this.tempFilePath = res.tempFilePath; this.recording = false; clearInterval(this.vInterval) this.$apply(); let duration = Math.ceil(res.duration/1000); //這里進行錄音結束之后的下一步操作this.showCancelType = 1; this.$apply(); } }); RecorderManager.start({ duration: 60000, format: 'mp3' }); this.startPageY = e.touches[0].clientY; this.showCancelType = 2; this.$apply(); }, onTouchMove(e) { this.recording = true; if (this.startPageY - e.touches[0].clientY > 50) { //松開手指 this.showCancelType = 3; } else { //上划取消 this.showCancelType = 2; } this.$apply(); console.log('onTouchMove'); }, onTouchEnd() { console.log('onTouchEnd'); const RecorderManager = wx.getRecorderManager(); RecorderManager.stop(); },