0%

js-audio-recorder组件实现录音

本文范例代码使用 Vue2.0 开发

一、安装 js-audio-recorder

1
npm install js-audio-recorder

二、在需要使用录音的页面中引入

Translate.vue
1
import Recorder from "js-audio-recorder";

三、声明录音对象

1
2
3
4
5
recorder: new Recorder({
sampleBits: 16, // 采样位数,支持 8 或 16,默认是16
sampleRate: 16000, // 采样率,支持 11025、16000、22050、24000、44100、48000,根据浏览器默认值,我的chrome是48000
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 // 先声明this的指向
// 服务器需要https协议或者设置一下浏览器
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, // 采样位数,支持 8 或 16,默认是16
sampleRate: 16000, // 采样率,支持 11025、16000、22050、24000、44100、48000,根据浏览器默认值,我的chrome是48000
numChannels: 1, // 声道,支持 1 或 2, 默认是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);

// 销毁录音实例,置为null释放资源,fn为回调函数,
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的协议
赏包辣条吃吧