背景: 在开发中,通过浏览器录音发现拿到的文件没有比特率,导致服务端无法解析语音的文字,所以四处寻找,找到了这个插件,经过调整,发现能满足开发需求,音频也可以灵活配置比特率,使音频更清晰了
1.安装 js-audio
npm i js-audio-recorder
2.新建组件MP3
<template>
<div>
<div class="AudioRecorder2"></div>
<button @click="startRecordAudio">开始录音</button>
<button @click="stopRecordAudio">终止录音</button>
<button @click="playRecordAudio">playRecordAudio</button>
<audio ref="audioPlayer" controls></audio>
</div>
</template>
<script>
import { audio_fileFun } from '@/api/TrendAnalysis';
import Recorder from 'js-audio-recorder'
export default {
name: 'AudioRecorder2',
components: {},
data() {
return {
recorder: new Recorder({
sampleBits: 16,
sampleRate: 16000,
numChannels: 1,
playTimer: null,
isrecording: false,
isDestory: false
})
}
},
mounted() {
this.$nextTick(() => {
this.startRecordAudio()
})
},
beforeDestroy() {
this.isDestory = true
this.stopRecordAudio()
},
destroyed() {
console.log('录音实例销毁-----------')
this.recorder.destroy().then(() => {
this.recorder = null
})
},
methods: {
startRecordAudio() {
if (this.isDestory) {
return
}
Recorder.getPermission().then(
(res) => {
console.log('开始录音=============', res)
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()
},
uploadWAVData() {
const fileName = '一把过啊兄弟-20221214172357.mp3 '
const wavBlob = this.recorder.getWAVBlob()
const formData = new FormData()
const newbolb = new Blob([wavBlob], { type: 'audio/mp3' })
const fileOfBlob = new File([newbolb], fileName)
formData.append('audio_file', newbolb)
this.$refs.audioPlayer.src = fileOfBlob
audio_fileFun(formData).then((res) => {
console.log(res)
});
},
handleSaveFile(id) {
const params = {
fileIds: [id],
subjectIcfRecordId: this.subjectIcfRecordId
}
}
}
}
</script>
<style></style>
3.引入组件
<mp3 />