小程序實現長按錄音,上劃取消發送
2020-09-27|HiShop
導讀:使用mpvue開發小程序時,可能需要用到錄音功能,可以通過使用"長按錄音松開發送,上劃取消發送"來實現小程序錄音功能。以下為大家整理官方文檔...
使用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, //發送鎖,當為true時上鎖,false時解鎖發送},
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 }];//contents是存儲錄音結束后的數據結構,用于渲染. } }); }
2.3. 長按錄音方法
在這個方法中需要做的事:
- 記錄長按的點信息,用于后面計算手指滑動的距離,實現上滑取消發送.
- 做一些界面樣式的控制.
- 開始錄音
handleRecordStart(e) { //longpress時觸發 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//先定義個60秒,后面可以手動調用wx.hideToast()隱藏 }); this.sendLock = false;//長按時是不上鎖的。 },
2.4. 松開發送
在這個方法中需要做的事:
- 做一些樣式的控制.
- 結束錄音.
handleRecordStop() { // touchend(手指松開)時觸發 this.record = {//復原在start方法中修改的錄音的數據結構 text: "長按錄音", type: "record", iconPath: require("@/../static/icons/record.png"), handler: this.handleRecordStart }; wx.hideToast();//結束錄音、隱藏Toast提示框 this.recorderManager.stop();//結束錄音 }
2.5. 上劃取消發送
在這個方法中需要做的事:
- 計算手指上滑的距離
- 根據距離判斷是否需要取消發送
- 如果取消發送,最重要的是this.sendLock = true,上鎖不發送
handleTouchMove(e) { //touchmove時觸發 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;//上劃距離不足,依然可以發送,不上鎖 } }, }
以上就是這篇小程序實現長按錄音,上劃取消發送 ,需要更多小程序開發內容,可以查看本網站,謝謝。
HiShop小程序工具提供多類型商城/門店小程序制作,可視化編輯 1秒生成5步上線。通過拖拽、拼接模塊布局小程序商城頁面,所看即所得,只需要美工就能做出精美商城。更多小程序請查看:小程序商店
您可能感興趣:小程序開發
上一篇:百度智能小程序怎么做,百度智能小程序如何申請 下一篇:微信小程序開發文檔tip