uniapp制作h5端小程序端一键录音功能
如图
上代码
<template>
<view class="record-container">
<button @touchstart="startRecord" @touchend="endRecord">按住说话,松开结束</button>
<button @tap="playVoice">播放录音</button>
<view class="status">录音中{{intIntervalTime}}s>>></view>
</view>
</template>
<script>
const recorderManager = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = true;
export default {
data() {
return {
text: "uni-app",
voicePath: "",
isRecord: false, // 记录状态,录音中或者是未开始
intervalTime: 0,
timer: null
};
},
onLoad() {
let self = this;
recorderManager.onStop(function(res) {
console.log("录音停止了" + JSON.stringify(res)); //返回录音的临时保存地址, 可用于后面的播放
self.voicePath = res.tempFilePath;
});
},
computed: {
intIntervalTime() {
// 用于显示整数的秒数
console.log(Math.round(this.intervalTime));
return Math.round(this.intervalTime);
}
},
methods: {
startRecord() {
this.timer = setInterval(() => {
this.intervalTime += 0.5;
if (this.intervalTime >= 0.5 && !this.isRecord) {
//如果用户录制的时间太短,就不会去开启录音, 因为有个bug: recorderManager.stop()在短时间内开启在关闭的话,实际上他还在不停地录音,不知道你们有没有遇到过
console.log("开始录音");
this.isRecord = true;
this.intervalTime = 0;
recorderManager.start({
format: "mp3"
});
}
}, 500);
},
endRecord() {
if (this.intervalTime <= 0.5) {
console.log("录音太短了!!!");
}
clearInterval(this.timer);
if (this.isRecord) {
setTimeout(() => {
recorderManager.stop();
this.isRecord = false;
console.log(this.isRecord);
}, 500); //延迟小段时间停止录音, 更好的体验
}
},
playVoice() {
console.log("播放录音");
if (this.voicePath) {
console.log(this.voicePath)
innerAudioContext.src = this.voicePath;
innerAudioContext.play();
}
}
}
};
</script>
<style>
.record-container {
padding-top: 100upx;
}
.status {
text-align: center;
}
</style>
/* 语音输入 */
.Voice_input{
border-bottom: 1px solid rgba(215,215,215,0.50);
}
.audiodiv{
padding-bottom: 50px;
}
.Voice_title{
height: 41px;
line-height: 41px;
font-family: PingFangSC-Regular;
font-size: 16px;
color: #1F1F26;
}
.speak_btn{
width: 178px;
height: 30px;
background-image: linear-gradient(180deg, #FFFFFF 0%, #F1F1F1 100%);
border: 1px solid #E8E8E8;
border-radius: 15.5px;
margin: 0 auto;
text-align: center;
line-height: 30px;
font-family: PingFangSC-Regular;
font-size: 14px;
color: #AAAAAA;
text-align: center;
margin-bottom: 15px;
}
.talkbtn{
color: #cccccc;
font-size: 11px;
border: 1rpx solid #cccccc;
border-radius: 40rpx;
margin-top: 5px;
position: absolute;
left: 50%;
transform:translate(-50%,0);
background: #f2f6fa;
}
.showaudio{
position: fixed;
left: 800rpx;
top: 0;
width: 213px;
height: 28px;
}