WXML代码:
<view class="chat-option">
<view class="msg-inp">
<button type="button" hover-class="hoverbtn" bindtouchstart="touchStart" bindtouchend="touchEnd">按住说话录音</button>
<button type="button" bindtap="playVoice">播放录音</button>
</view>
</view>
WXSS代码:
.chat-option{width:100%;background-color:#e6e6e6;position: fixed;bottom: 0;display: flex;padding: 40rpx 20rpx;align-items: center;}
.chat-option .msg-inp{width: 100%;display: flex;}
.chat-option .msg-inp button{height: 80rpx;width: 40%;background-color: #fff;margin: 0 0 0 5%;border-radius: 20rpx;font-size: 30rpx;color: #e2e2e2;background-color: #8e8e8e;font-weight: initial;}
.chat-option .msg-inp button.hoverbtn{background-color: #828282;}
JS代码:
Page({
data: {
voiceIndex: 1,
voiceInter: '',
tempFilePaths: ''
},
//按住说话
touchStart(){
let that = this;
wx.showLoading({
title: '录音中'
});
let rec = wx.getRecorderManager();
let options = {
sampleRate: 44100, //采样率
encodeBitRate: 192000, //编码码率
format: 'mp3' //音频格式
}
that.data.voiceInter = setInterval(() => {
that.data.voiceIndex++;
}, 350);
rec.start(options);
},
//松开停止
touchEnd(){
let that = this;
wx.hideLoading();
let rec = wx.getRecorderManager();
if(that.data.voiceIndex > 1){
that.clearInterTime();
rec.stop();
rec.onStop((res) => {
//录音文件临时地址
that.setData({
tempFilePaths: res.tempFilePath
});
});
}else{
that.clearInterTime();
return;
}
},
//播放录音
playVoice(){
let that = this;
let adc = wx.createInnerAudioContext();
adc.src = that.data.tempFilePaths;
adc.play();
wx.showLoading({
title: '录音播放中'
});
adc.onEnded((res) => {
wx.hideLoading();
});
},
//定时清理
clearInterTime(){
let that = this;
that.setData({voiceIndex: 1});
clearInterval(that.data.voiceInter);
},
})