本篇内容主要讲解“小程序如何实现长按录音,上划取消发送功能”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“小程序如何实现长按录音,上划取消发送功能”吧!
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. 上划取消发送
在这个方法中需要做的事:
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;//上划距离不足,依然可以发送,不上锁
}
},
}
到此,相信大家对“小程序如何实现长按录音,上划取消发送功能”有了更深的了解,不妨来实际操作一番吧!这里是天达云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!