vue实现视频录制功能
使用Vue实现视频录制功能
准备工作
确保项目已安装Vue.js环境,推荐使用Vue 3版本。需要浏览器支持getUserMedia和MediaRecorder API,现代浏览器如Chrome、Firefox、Edge等均支持。
安装依赖
视频录制功能通常不需要额外依赖,但若需处理复杂逻辑可安装recordrtc库:
npm install recordrtc
核心实现步骤
获取用户摄像头权限
通过navigator.mediaDevices.getUserMedia获取视频流:

async function startCamera() {
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: true
});
this.localStream = stream;
this.$refs.videoElement.srcObject = stream;
} catch (error) {
console.error("Error accessing media devices:", error);
}
}
初始化录制器
使用MediaRecorder API初始化录制:
function initRecorder() {
const options = { mimeType: 'video/webm' };
this.mediaRecorder = new MediaRecorder(this.localStream, options);
this.chunks = [];
this.mediaRecorder.ondataavailable = (e) => {
if (e.data.size > 0) this.chunks.push(e.data);
};
this.mediaRecorder.onstop = () => {
const blob = new Blob(this.chunks, { type: 'video/webm' });
this.recordedUrl = URL.createObjectURL(blob);
};
}
控制录制过程 提供开始/停止录制按钮的交互逻辑:

function startRecording() {
this.isRecording = true;
this.chunks = [];
this.mediaRecorder.start();
}
function stopRecording() {
this.isRecording = false;
this.mediaRecorder.stop();
}
组件模板示例
<template>
<div>
<video ref="videoElement" autoplay muted></video>
<button @click="startCamera">开启摄像头</button>
<button @click="startRecording" :disabled="!localStream || isRecording">
开始录制
</button>
<button @click="stopRecording" :disabled="!isRecording">
停止录制
</button>
<video v-if="recordedUrl" :src="recordedUrl" controls></video>
</div>
</template>
进阶功能扩展
录制参数配置 支持自定义视频分辨率、帧率和音频采样率:
const constraints = {
video: {
width: 1280,
height: 720,
frameRate: 30
},
audio: {
sampleRate: 44100,
channelCount: 2
}
};
文件下载功能 添加下载按钮将录制视频保存为文件:
function downloadVideo() {
const a = document.createElement('a');
a.href = this.recordedUrl;
a.download = 'recording.webm';
a.click();
}
注意事项
- 需在HTTPS环境或localhost下使用媒体设备API
- 移动端需处理设备旋转导致的画面方向问题
- 不同浏览器支持的视频格式可能不同,建议检测
MediaRecorder.isTypeSupported()
完整示例组件
export default {
data() {
return {
localStream: null,
mediaRecorder: null,
chunks: [],
isRecording: false,
recordedUrl: null
};
},
methods: {
// 包含上述所有方法
},
beforeUnmount() {
if (this.localStream) {
this.localStream.getTracks().forEach(track => track.stop());
}
}
};






