vue实现语音录制
Vue 实现语音录制的方法
使用 Web Audio API 和 MediaRecorder
安装必要的依赖(如需要):
npm install recordrtc
在 Vue 组件中引入相关库:
import RecordRTC from 'recordrtc';
创建录音功能的核心代码:
export default {
data() {
return {
recorder: null,
audioChunks: [],
audioBlob: null,
audioUrl: null,
isRecording: false
};
},
methods: {
async startRecording() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
this.recorder = new RecordRTC(stream, {
type: 'audio',
mimeType: 'audio/wav'
});
this.recorder.startRecording();
this.isRecording = true;
} catch (error) {
console.error('Error accessing microphone:', error);
}
},
stopRecording() {
if (!this.recorder) return;
this.recorder.stopRecording(() => {
this.audioBlob = this.recorder.getBlob();
this.audioUrl = URL.createObjectURL(this.audioBlob);
this.isRecording = false;
this.recorder.destroy();
this.recorder = null;
});
}
}
};
使用 vue-voice-recorder 插件
安装插件:
npm install vue-voice-recorder
在 Vue 项目中注册组件:
import VueVoiceRecorder from 'vue-voice-recorder';
Vue.use(VueVoiceRecorder);
在模板中使用:
<template>
<div>
<voice-recorder
@start="onStart"
@stop="onStop"
@error="onError"
@stream="onStream"
/>
<audio v-if="audioUrl" :src="audioUrl" controls></audio>
</div>
</template>
使用浏览器原生 API
纯浏览器 API 实现方案:
export default {
methods: {
async startNativeRecording() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
this.mediaRecorder = new MediaRecorder(stream);
this.audioChunks = [];
this.mediaRecorder.ondataavailable = event => {
this.audioChunks.push(event.data);
};
this.mediaRecorder.onstop = () => {
this.audioBlob = new Blob(this.audioChunks);
this.audioUrl = URL.createObjectURL(this.audioBlob);
};
this.mediaRecorder.start();
} catch (err) {
console.error('Error:', err);
}
},
stopNativeRecording() {
if (this.mediaRecorder) {
this.mediaRecorder.stop();
this.mediaRecorder.stream.getTracks().forEach(track => track.stop());
}
}
}
};
注意事项
确保在 HTTPS 环境下测试,某些浏览器在非安全环境下会限制录音功能
iOS 设备有特殊限制,需要用户主动交互才能启动录音
录音前需要获取用户授权,处理可能的权限拒绝情况
不同浏览器支持的音频格式可能不同,建议测试目标浏览器的兼容性
录音文件大小可能较大,上传前考虑压缩或分段处理







