vue实现音频录音
Vue 实现音频录音的方法
使用浏览器 MediaRecorder API
浏览器原生提供的 MediaRecorder API 是录制音频的核心工具。通过 navigator.mediaDevices.getUserMedia 获取麦克风权限后,可初始化录音功能。
// 在 Vue 组件中
export default {
data() {
return {
mediaRecorder: null,
audioChunks: [],
audioBlob: null,
audioUrl: ''
}
},
methods: {
async startRecording() {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
this.mediaRecorder = new MediaRecorder(stream);
this.mediaRecorder.ondataavailable = (event) => {
this.audioChunks.push(event.data);
};
this.mediaRecorder.start();
},
stopRecording() {
return new Promise((resolve) => {
this.mediaRecorder.onstop = () => {
this.audioBlob = new Blob(this.audioChunks, { type: 'audio/wav' });
this.audioUrl = URL.createObjectURL(this.audioBlob);
resolve(this.audioBlob);
};
this.mediaRecorder.stop();
});
}
}
}
添加录音控制按钮
在模板中添加按钮控制录音开始和结束,并播放录音结果。
<template>
<div>
<button @click="startRecording" :disabled="isRecording">开始录音</button>
<button @click="stopRecording" :disabled="!isRecording">停止录音</button>
<audio v-if="audioUrl" :src="audioUrl" controls></audio>
</div>
</template>
处理录音权限问题
需处理用户拒绝麦克风权限的情况,通过 catch 捕获错误。
startRecording() {
navigator.mediaDevices.getUserMedia({ audio: true })
.then((stream) => {
this.mediaRecorder = new MediaRecorder(stream);
// 其他初始化代码
})
.catch((err) => {
console.error('麦克风权限被拒绝:', err);
});
}
录音格式与兼容性
MediaRecorder 支持多种音频格式,但不同浏览器兼容性不同。可通过 mimeType 指定格式。
const options = { mimeType: 'audio/webm' }; // Chrome 首选
this.mediaRecorder = new MediaRecorder(stream, options);
第三方库简化流程
若需更复杂功能(如可视化、格式转换),可使用 recordrtc 或 wavesurfer.js 等库。
安装 recordrtc:
npm install recordrtc
使用示例:
import RecordRTC from 'recordrtc';
export default {
methods: {
async startRecording() {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
this.recorder = new RecordRTC(stream, { type: 'audio' });
this.recorder.startRecording();
},
stopRecording() {
return new Promise((resolve) => {
this.recorder.stopRecording(() => {
resolve(this.recorder.getBlob());
});
});
}
}
}
注意事项
- 仅在 HTTPS 或 localhost 环境下可用,部分浏览器不允许 HTTP 访问麦克风。
- 移动端浏览器可能有额外限制,需测试目标平台兼容性。
- 长时间录音需注意内存管理,及时释放
Blob对象。







