1、安装插件
npm i js-audio-recorder
2、封装AudioRecorder.vue
组件
<template>
<div class="AudioRecorder2"></div>
</template>
<script>
import Recorder from 'js-audio-recorder'
import { fileuploadext, processfilesave } from '@/api/user.js'
import { mapGetters } from 'vuex'
import moment from 'moment'
export default {
name: 'AudioRecorder2',
components: {},
data() {
return {
recorder: new Recorder({
sampleBits: 16, // 采样位数,支持 8 或 16,默认是16
sampleRate: 16000, // 采样率,支持 11025、16000、22050、24000、44100、48000,根据浏览器默认值,我的chrome是48000
numChannels: 1, // 声道,支持 1 或 2, 默认是1
// compiling: false,(0.x版本中生效,1.x增加中) // 是否边录边转换,默认是false
playTimer: null,
isrecording: false, // 当前是否在录音
isDestory: false // 是否销毁
})
}
},
computed: {
...mapGetters({
subjectIcfRecordId: 'subjectIcfRecordId',
subjectId: 'subjectId'
})
},
watch: {},
created() {},
mounted() {
this.$nextTick(() => {
this.startRecordAudio()
})
},
beforeDestroy() {
this.isDestory = true // 准备销毁
this.stopRecordAudio()
},
destroyed() {
console.log('录音实例销毁-----------')
// 销毁录音实例,置为null释放资源,fn为回调函数,
this.recorder.destroy().then(() => {
this.recorder = null
})
},
methods: {
// 开始录音
startRecordAudio() {
if (this.isDestory) {
return
}
Recorder.getPermission().then(
() => {
console.log('开始录音=============')
this.recorder.start() // 开始录音
this.isrecording = true // 录制中
setTimeout(() => {
this.stopRecordAudio()
}, 1000 * 60 * 10)
},
error => {
console.log('======请先允许该网页使用麦克风')
console.log(`${error.name} : ${error.message}`)
}
)
},
// 停止录音
stopRecordAudio() {
if (this.isrecording) {
console.log('停止录音-----------------')
this.isrecording = false
this.recorder.stop()
this.uploadWAVData()
} else {
console.log('没有需要停止的录音------------')
}
},
// 播放录音
playRecordAudio() {
console.log('播放录音')
this.recorder.play()
},
// 上传wav录音数据获取文件id
uploadWAVData() {
// 格式: subject-张大宝-知情过程录音-20221214172357.mp3
const time = moment().format('YYYYMMDDHHmmss')
const fileName = `subject-${this.subjectId}-知情过程录音-${time}.mp3`
var wavBlob = this.recorder.getWAVBlob()
// 创建一个formData对象
var formData = new FormData()
const newbolb = new Blob([wavBlob], { type: 'audio/mp3' })
// 获取当时时间戳作为文件名
const fileOfBlob = new File([newbolb], fileName)
formData.append('file', fileOfBlob)
formData.append('fileName', fileName)
fileuploadext(formData).then(({ success, data }) => {
if (success) {
this.handleSaveFile(data.fileId)
}
})
},
// 保存录音文件
handleSaveFile(id) {
const params = {
fileIds: [id],
subjectIcfRecordId: this.subjectIcfRecordId
}
processfilesave(params).then(res => {
if (res.success) {
console.log('录制文件上传成功=======================')
this.startRecordAudio() // 循环录制
}
})
}
}
}
</script>
<style></style>
3、使用
<template>
<!-- 电子录音 -->
<AudioRecorder v-if='flag' ref='audioRecorder'/>
</template>
<script>
import AudioRecorder from '@/components/AudioRecorder'
</script>
当前组件AudioRecorder
中场景是组件创建即开始录音,销毁即停止录音,可根据场景自动修改
或者通过this.$refs.audioRecorder.playRecordAudio()
等方式调用组件内录音方法