vue实现录制视频
Vue 实现录制视频的方法
使用 MediaDevices API 和 MediaRecorder
Vue 中可以通过浏览器提供的 MediaDevices API 和 MediaRecorder API 实现视频录制功能。以下是一个基本的实现步骤:
<template>
<div>
<video ref="videoRef" autoplay muted></video>
<button @click="startRecording">开始录制</button>
<button @click="stopRecording">停止录制</button>
<video v-if="recordedUrl" :src="recordedUrl" controls></video>
</div>
</template>
<script>
export default {
data() {
return {
mediaStream: null,
mediaRecorder: null,
recordedChunks: [],
recordedUrl: null,
};
},
methods: {
async startRecording() {
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: true,
});
this.mediaStream = stream;
this.$refs.videoRef.srcObject = stream;
this.mediaRecorder = new MediaRecorder(stream);
this.mediaRecorder.ondataavailable = (event) => {
if (event.data.size > 0) {
this.recordedChunks.push(event.data);
}
};
this.mediaRecorder.start();
} catch (error) {
console.error('Error accessing media devices:', error);
}
},
stopRecording() {
this.mediaRecorder.stop();
this.mediaStream.getTracks().forEach((track) => track.stop());
const blob = new Blob(this.recordedChunks, { type: 'video/webm' });
this.recordedUrl = URL.createObjectURL(blob);
this.recordedChunks = [];
},
},
};
</script>
使用第三方库
如果需要更复杂的功能,可以考虑使用第三方库如 recordrtc 或 vue-video-recorder。
安装 recordrtc:
npm install recordrtc
示例代码:
import RecordRTC from 'recordrtc';
// 在 Vue 方法中使用
startRecording() {
navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then((stream) => {
this.mediaStream = stream;
this.$refs.videoRef.srcObject = stream;
this.mediaRecorder = new RecordRTC(stream, { type: 'video' });
this.mediaRecorder.startRecording();
});
}
stopRecording() {
this.mediaRecorder.stopRecording(() => {
const blob = this.mediaRecorder.getBlob();
this.recordedUrl = URL.createObjectURL(blob);
this.mediaStream.getTracks().forEach((track) => track.stop());
});
}
注意事项
- 确保在 HTTPS 环境下使用 MediaDevices API,否则可能无法正常工作。
- 不同浏览器对视频格式的支持可能不同,建议测试兼容性。
- 录制完成后,记得释放资源,如停止媒体流和释放 URL 对象。
保存录制的视频
如果需要将录制的视频保存到服务器,可以使用 FormData 上传:

const formData = new FormData();
formData.append('video', blob, 'recording.webm');
axios.post('/upload', formData).then((response) => {
console.log('Upload successful', response);
});
以上方法提供了在 Vue 中实现视频录制的基本方案,可以根据实际需求进行调整和扩展。






