vue实现视频录制
Vue 实现视频录制的方法
使用浏览器 MediaDevices API
通过 navigator.mediaDevices.getUserMedia 获取摄像头和麦克风权限,结合 MediaRecorder API 实现录制:

// 在Vue组件中
data() {
return {
mediaStream: null,
mediaRecorder: null,
recordedChunks: [],
videoUrl: ''
}
},
methods: {
async startRecording() {
try {
this.mediaStream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: true
});
this.mediaRecorder = new MediaRecorder(this.mediaStream);
this.mediaRecorder.ondataavailable = (e) => {
if (e.data.size > 0) {
this.recordedChunks.push(e.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.videoUrl = URL.createObjectURL(blob);
this.recordedChunks = [];
}
}
使用第三方库 vue-video-recorder
安装依赖:

npm install vue-video-recorder
组件使用示例:
import VueVideoRecorder from 'vue-video-recorder'
export default {
components: {
VueVideoRecorder
},
methods: {
handleRecordingComplete(videoBlob) {
const videoUrl = URL.createObjectURL(videoBlob);
// 处理录制完成的视频
}
}
}
实现屏幕录制
使用 getDisplayMedia 代替 getUserMedia 实现屏幕录制:
async startScreenRecording() {
try {
this.mediaStream = await navigator.mediaDevices.getDisplayMedia({
video: true,
audio: true
});
// 其余逻辑与摄像头录制相同
} catch (error) {
console.error('Screen sharing error:', error);
}
}
注意事项
- 需要HTTPS环境或localhost才能使用媒体设备API
- 不同浏览器对视频格式支持可能不同
- 移动端可能需要额外权限处理
- 录制时长受浏览器内存限制
完整组件示例
<template>
<div>
<video ref="preview" autoplay muted></video>
<button @click="startRecording">开始录制</button>
<button @click="stopRecording">停止录制</button>
<video v-if="videoUrl" :src="videoUrl" controls></video>
</div>
</template>
<script>
export default {
data() {
return {
mediaStream: null,
mediaRecorder: null,
recordedChunks: [],
videoUrl: ''
}
},
methods: {
async startRecording() {
try {
this.mediaStream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: true
});
this.$refs.preview.srcObject = this.mediaStream;
this.mediaRecorder = new MediaRecorder(this.mediaStream);
this.mediaRecorder.ondataavailable = (e) => {
if (e.data.size > 0) {
this.recordedChunks.push(e.data);
}
};
this.mediaRecorder.start(1000); // 每1秒收集一次数据
} catch (error) {
console.error('Error:', error);
}
},
stopRecording() {
this.mediaRecorder.stop();
this.mediaStream.getTracks().forEach(track => track.stop());
const blob = new Blob(this.recordedChunks, { type: 'video/webm' });
this.videoUrl = URL.createObjectURL(blob);
this.recordedChunks = [];
}
}
}
</script>






