vue实现通话录音
实现通话录音的基本思路
在Vue中实现通话录音功能需要结合浏览器的Web Audio API和MediaRecorder API。以下是一个完整的实现方案,分为录音功能封装和Vue组件集成两部分。
录音功能封装
创建一个独立的录音工具类(recorder.js),封装核心录音逻辑:
class AudioRecorder {
constructor() {
this.mediaStream = null;
this.mediaRecorder = null;
this.chunks = [];
}
async start() {
try {
this.mediaStream = await navigator.mediaDevices.getUserMedia({ audio: true });
this.mediaRecorder = new MediaRecorder(this.mediaStream);
this.mediaRecorder.ondataavailable = (e) => {
this.chunks.push(e.data);
};
this.mediaRecorder.start();
return true;
} catch (error) {
console.error('录音启动失败:', error);
return false;
}
}
stop() {
return new Promise((resolve) => {
this.mediaRecorder.onstop = () => {
const blob = new Blob(this.chunks, { type: 'audio/wav' });
this.chunks = [];
resolve(blob);
};
this.mediaRecorder.stop();
this.mediaStream.getTracks().forEach(track => track.stop());
});
}
}
export default AudioRecorder;
Vue组件集成
创建录音组件(VoiceRecorder.vue):
<template>
<div class="recorder-container">
<button @click="toggleRecording" :disabled="isProcessing">
{{ isRecording ? '停止录音' : '开始录音' }}
</button>
<audio v-if="audioUrl" :src="audioUrl" controls></audio>
<button v-if="audioUrl" @click="downloadRecording">下载录音</button>
</div>
</template>
<script>
import AudioRecorder from './recorder';
export default {
data() {
return {
isRecording: false,
isProcessing: false,
audioUrl: '',
recorder: new AudioRecorder()
};
},
methods: {
async toggleRecording() {
if (this.isRecording) {
this.isProcessing = true;
const audioBlob = await this.recorder.stop();
this.audioUrl = URL.createObjectURL(audioBlob);
this.$emit('record-complete', audioBlob);
this.isRecording = false;
this.isProcessing = false;
} else {
const success = await this.recorder.start();
if (success) {
this.isRecording = true;
this.audioUrl = '';
}
}
},
downloadRecording() {
const a = document.createElement('a');
a.href = this.audioUrl;
a.download = `recording_${new Date().toISOString()}.wav`;
a.click();
}
},
beforeDestroy() {
if (this.isRecording) {
this.recorder.stop();
}
}
};
</script>
权限处理
在public/index.html中添加麦克风权限请求的元信息:
<meta name="microphone" content="microphone">
服务器端存储(可选)
如果需要将录音保存到服务器,可以添加以下方法:
async uploadRecording(blob) {
const formData = new FormData();
formData.append('audio', blob, 'recording.wav');
try {
const response = await fetch('/api/upload', {
method: 'POST',
body: formData
});
return await response.json();
} catch (error) {
console.error('上传失败:', error);
throw error;
}
}
注意事项
-
浏览器兼容性:MediaRecorder API在不同浏览器中支持程度不同,建议在使用前检测功能支持:
if (!navigator.mediaDevices || !window.MediaRecorder) { alert('您的浏览器不支持录音功能'); } -
HTTPS要求:大多数浏览器要求页面通过HTTPS加载才能使用麦克风。
-
录音质量:可以通过配置MediaRecorder的mimeType参数调整录音质量:
const options = { mimeType: 'audio/webm' }; this.mediaRecorder = new MediaRecorder(this.mediaStream, options); -
录音时长限制:某些浏览器对单次录音时长有限制,需要分段处理长时间录音。
-
移动端适配:移动设备可能需要额外的用户交互才能启动录音。
实现完成后,可以在其他组件中引入并使用录音组件:

<template>
<voice-recorder @record-complete="handleRecording"/>
</template>






