小小记录一下项目中用到的录音功能
1.下载插件
npm i js-audio-recorder
2.展示代码
<template><div style="padding: 20px;"><div style="font-size:14px"><h3>录音时长:{{ recorder && recorder.duration.toFixed(0) }}s</h3><br /><button type="primary" @click="handleStart">开始录音</button><button type="warning" @click="handleStop">停止录音</button><br /><br /><h3>播放时长:{{recorder &&(playTime > recorder.duration? recorder.duration.toFixed(0): playTime.toFixed(0))}}s</h3><br /><button type="primary" @click="handlePlay">播放录音</button><button type="info" @click="handlePausePlay">暂停播放</button><button type="success" @click="handleResumePlay">继续播放</button><button type="warning" @click="handleStopPlay">停止播放</button><button type="primary" @click="uploadRecord">上传</button></div></div>
</template><script>
import Recorder from 'js-audio-recorder'
const parameter = {sampleBits: 8, // 采样位数,支持 8 或 16,默认是16sampleRate: 11025, // 采样率,支持 11025、16000、22050、24000、44100、48000,根据浏览器默认值,我的chrome是48000numChannels: 1 // 声道,支持 1 或 2, 默认是1
}
export default {data() {return {recorder: null,playTime: 0,timer: null,src: null,setTime:0}},created() {this.recorder = new Recorder(parameter)},methods: {// 开始录音handleStart() {var that = thisthat.recorder = new Recorder()Recorder.getPermission().then(() => {console.log('开始录音')that.recorder.start()// 开始录音
//限制录音时长that.setTime= setTimeout(function(){that.handleStop()alert('录音时间到')},180000)}, (error) => {that.$message({message: '请先允许该网页使用麦克风',type: 'info'})console.log(`${error.name} : ${error.message}`)})},handleStop() {console.log('停止录音')this.recorder.stop() // 停止录音clearTimeout(this.setTime)// this.recorder.duration= 0;console.log('时长',this.recorder.duration)},handlePlay() {console.log('播放录音')console.log(this.recorder)this.recorder.play() // 播放录音// 播放时长this.timer = setInterval(() => {try {this.playTime = this.recorder.getPlayTime()} catch (error) {this.timer = null}}, 100)},handlePausePlay() {console.log('暂停播放')this.recorder.pausePlay() // 暂停播放// 播放时长this.playTime = this.recorder.getPlayTime()this.time = null},handleResumePlay() {console.log('恢复播放')this.recorder.resumePlay() // 恢复播放// 播放时长this.timer = setInterval(() => {try {this.playTime = this.recorder.getPlayTime()} catch (error) {this.timer = null}}, 100)},handleStopPlay() {console.log('停止播放')this.recorder.stopPlay() // 停止播放// 播放时长this.playTime = this.recorder.getPlayTime()this.timer = null},handleDestroy() {console.log('销毁实例')this.recorder.destroy() // 毁实例this.timer = null},uploadRecord() {if (this.recorder == null || this.recorder.duration === 0) {console.log('请先录音')// this.$message({// message: '请先录音',// type: 'error'// })return false}this.recorder.pause() // 暂停录音this.timer = nullconsole.log('上传录音')// 上传录音const formData = new FormData()const blob = this.recorder.getWAVBlob()// 获取wav格式音频数据// 此处获取到blob对象后需要设置fileName满足当前项目上传需求,其它项目可直接传把blob作为file塞入formDataconst newbolb = new Blob([blob], { type: 'audio/wav' })const fileOfBlob = new File([newbolb], new Date().getTime() + '.wav')formData.append('file', fileOfBlob)const url = window.URL.createObjectURL(fileOfBlob)//通过blob对象获取到播放urlthis.src = urlconsole.log(blob)// const axios = require('axios')上传后台// axios.post(url, formData).then(res => {// console.log(res.data.data[0].url)// })}}
}
</script>
重点:最后发现停止录音还会占用录音权限
稍作修改(停止录音把录音文件传入blob,关闭录音用到销毁实例会删除这个流让录音的小标志消失)
1.
// 开始录音handleStart() {var that = this;that.recorder = new Recorder();Recorder.getPermission().then(() => {that.kFlag = false;that.dFlag = true;console.log("开始录音");that.recorder.start(); // 开始录音clearTimeout(this.setTime);that.setTime = setTimeout(function () {that.stopRecord();alert("录音时间到");}, 180000);},(error) => {that.$message({message: "请先允许该网页使用麦克风",type: "info",});console.log(`${error.name} : ${error.message}`);});},
2.
stopRecord() {if (this.recorder == null || this.recorder.duration === 0) {Dialog({message: `<div style="font-size:18px;">请先录音</div>`,width: 200,height: 50,});return false;}console.log("停止录音");this.kFlag = true;this.dFlag = false;this.recorder.stop(); // 停止录音// this.drawRecordId && cancelAnimationFrame(this.drawRecordId);// this.drawRecordId = null;clearTimeout(this.setTime);const formData = new FormData();this.blob = this.recorder.getWAVBlob(); // 获取wav格式音频数据// 此处获取到blob对象后需要设置fileName满足当前项目上传需求,其它项目可直接传把blob作为file塞入formDataconst newbolb = new Blob([this.blob], { type: "audio/wav" });const fileOfBlob = new File([newbolb], new Date().getTime() + ".wav");formData.append("file", fileOfBlob);const url = window.URL.createObjectURL(fileOfBlob); //通过blob对象获取到播放urlthis.src = url;console.log(this.blob);},
3.
handleStop() {console.log("关闭录音");this.recorder.destroy(); // 毁实例console.log(this.blob);},
成果
需要其他效果可以通过
3.插件地址Introduction · recorder
自行添加