最近在使用mpvue开发小程序,需要用到录音功能,于是打算参照微信的录音方案:"长按录音松开发送,上划取消发送"。在网上找了一圈都没发现相似的案例,没办法只能自己实现。
下面讲解只贴上关键代码
1. html部分。
微信小程序事件接口:
//html部分 class部分只是控制样式 与功能无关分析:长按录音需要longpress事件,松开发送需要touchend事件,上滑取消发送需要touchmove事件。由此可有以下html代码
<div class="input weui-grid" hover-class="weui-grid_active" :class="record.type" @longpress="handleRecordStart" @touchmove="handleTouchMove" @touchend="handleRecordStop"> <image class="weui-grid__icon" :src="record.iconPath"/> <div class="weui-grid__label">{{record.text}}</div> </div>
2. JS部分
2.1. 首先定义录音的数据结构:
旧版的小程序录音接口wx.startRecord和wx.stopRecord在1.6.0版本后不再维护了,所以使用其建议的wx.getRecordManager接口。
注意:使用wx.getRecordManager接口的话,应调用相应的音频控制接口wx.createInnerAudioContext()来播放和控制录音.
data(){ record: { text: "长按录音", type: "record", iconPath: require("@/../static/icons/record.png"), handler: this.handleRecordStart }, recorderManager: wx.getRecorderManager(), startPoint: {}, sendLock: true, },
2.2. 监听录音stop
onLoad(){ this.recorderManager.onStop(res => { if (this.sendLock) { } else { if (res.duration < 1000) wx.showToast({ title: "录音时间太短", icon: "none", duration: 1000 }); else this.contents = [...this.contents,{ type: "record", content: res }]; } }); }
2.3. 长按录音方法
在这个方法中需要做的事:
- 记录长按的点信息,用于后面计算手指滑动的距离,实现上滑取消发送.
- 做一些界面样式的控制.
- 开始录音
handleRecordStart(e) { this.startPoint = e.touches[0]; this.record = { text: "松开发送", type: "recording", iconPath: require("@/../static/icons/recording.png"), handler: this.handleRecordStart }; this.recorderManager.start(); wx.showToast({ title: "正在录音,上划取消发送", icon: "none", duration: 60000 }); this.sendLock = false; },
2.4. 松开发送
在这个方法中需要做的事:
handleRecordStop() { this.record = { text: "长按录音", type: "record", iconPath: require("@/../static/icons/record.png"), handler: this.handleRecordStart }; wx.hideToast(); this.recorderManager.stop(); }
2.5. 上划取消发送
在这个方法中需要做的事:
- 计算手指上滑的距离
- 根据距离判断是否需要取消发送
- 如果取消发送,最重要的是this.sendLock = true,上锁不发送
handleTouchMove(e) { var moveLenght = e.touches[e.touches.length - 1].clientY - this.startPoint.clientY; if (Math.abs(moveLenght) > 50) { wx.showToast({ title: "松开手指,取消发送", icon: "none", duration: 60000 }); this.sendLock = true; } else { wx.showToast({ title: "正在录音,上划取消发送", icon: "none", duration: 60000 }); this.sendLock = false; } }, }
2.6. 演示GIF
|