vue实现录视频
Vue 实现录视频功能
使用浏览器 API 实现录屏
在 Vue 项目中可以通过浏览器提供的 MediaDevices API 和 MediaRecorder API 实现录屏功能。需要确保浏览器支持这些 API,通常在 Chrome、Firefox 等现代浏览器中可用。
<template>
<div>
<video ref="videoPreview" autoplay muted></video>
<button @click="startRecording">开始录制</button>
<button @click="stopRecording">停止录制</button>
<a v-if="videoUrl" :href="videoUrl" download="recorded-video.webm">下载视频</a>
</div>
</template>
<script>
export default {
data() {
return {
mediaStream: null,
mediaRecorder: null,
recordedChunks: [],
videoUrl: null
};
},
methods: {
async startRecording() {
try {
this.mediaStream = await navigator.mediaDevices.getDisplayMedia({
video: true,
audio: true
});
this.$refs.videoPreview.srcObject = this.mediaStream;
this.mediaRecorder = new MediaRecorder(this.mediaStream);
this.mediaRecorder.ondataavailable = (event) => {
if (event.data.size > 0) {
this.recordedChunks.push(event.data);
}
};
this.mediaRecorder.onstop = () => {
const blob = new Blob(this.recordedChunks, { type: 'video/webm' });
this.videoUrl = URL.createObjectURL(blob);
this.recordedChunks = [];
};
this.mediaRecorder.start();
} catch (error) {
console.error('Error accessing media devices:', error);
}
},
stopRecording() {
this.mediaRecorder.stop();
this.mediaStream.getTracks().forEach(track => track.stop());
}
}
};
</script>
使用第三方库实现录屏
如果需要更复杂的录屏功能,可以考虑使用第三方库如 recordrtc。
安装依赖:
npm install recordrtc
示例代码:
<template>
<div>
<video ref="videoPreview" autoplay muted></video>
<button @click="startRecording">开始录制</button>
<button @click="stopRecording">停止录制</button>
</div>
</template>
<script>
import RecordRTC from 'recordrtc';
export default {
data() {
return {
recorder: null,
stream: null
};
},
methods: {
async startRecording() {
try {
this.stream = await navigator.mediaDevices.getDisplayMedia({
video: true,
audio: true
});
this.$refs.videoPreview.srcObject = this.stream;
this.recorder = new RecordRTC(this.stream, {
type: 'video'
});
this.recorder.startRecording();
} catch (error) {
console.error('Error:', error);
}
},
async stopRecording() {
this.recorder.stopRecording(() => {
const blob = this.recorder.getBlob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'recorded-video.webm';
a.click();
this.stream.getTracks().forEach(track => track.stop());
});
}
}
};
</script>
注意事项
录屏功能需要用户授权,浏览器会弹出提示框请求用户同意分享屏幕。不同浏览器对录屏的支持程度可能不同,建议在实际使用前进行兼容性测试。
录制的视频格式通常是 webm,如果需要其他格式,可能需要使用转码工具。录屏功能在移动设备上的支持有限,主要适用于桌面端浏览器。







