js-audio-recorder 是一个基于 Web Audio API 的录音组件,它可以让你在浏览器中轻松地实现音频录制功能。它支持多种配置项,如采样位数、采样率、声道数等,可以满足不同的需求。同时,它还提供了边录边播的功能,可以让用户在录制的同时听到录制的声音。
本文范例代码使用 Vue2.0 开发
一、安装 js-audio-recorder
1
| npm install js-audio-recorder
|
二、在需要使用录音的页面中引入
Translate.vue1
| import Recorder from "js-audio-recorder";
|
三、声明录音对象
1 2 3 4 5
| recorder: new Recorder({ sampleBits: 16, sampleRate: 16000, numChannels: 1 }),
|
配置项:
1 2 3 4 5 6
| interface recorderConfig { sampleBits?: number; sampleRate?: number; numChannels?: number; compiling?: boolean; }
|
四、授权并开始录音
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| initRecorder() { let that = this if (typeof (navigator.mediaDevices.getUserMedia) == "undefined") { this.$message.error('当前没有语音权限!') return } if (navigator.mediaDevices.getUserMedia) { const constraints = { audio: true }; navigator.mediaDevices.getUserMedia(constraints).then(() => { console.log("授权成功!"); }, () => { console.error("授权失败!"); }); } else { console.error("浏览器不支持 getUserMedia"); } this.recorder = new Recorder({ sampleBits: 16, sampleRate: 16000, numChannels: 1, }); this.recorder.start().then(function () { console.log("开始录音...") }); },
|
五、结束录音
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| async sendSpeak() { this.recorder.stop(); let wavBlob = this.recorder.getWAVBlob() const fileName = new Date() let renameFile = new File([wavBlob], `${fileName}.wav`, { type: 'audio/wav' }) console.log(renameFile);
this.recorder.destroy().then(function () { baseData.recorder = null; });
const formData = new FormData(); formData.append('file', renameFile) formData.append('languageCode', this.inputValue.value) postTranslateOther(formData).then(res => { this.inputTextarea = res.data.data this.submit() }).catch(error => { console.log(error); }) },
|
注意:
- 使用
js-audio-recorder
时,必须得是https
的协议