页面代码
<button @click="startRecording">开始录制桌面</button>
<button @click="stopRecording" :disabled="!isRecording">结束录制</button>
js代码
// 录制桌面 保存到本地
methods:{
async startRecording() {
try {
// 请求访问桌面屏幕
const displayStream = await navigator.mediaDevices.getDisplayMedia({
video: true,
audio: true
});
// 初始化MediaRecorder
this.mediaRecorder = new MediaRecorder(displayStream, {
mimeType: 'video/webm; codecs=vp8'
});
// 数据可读取时的回调
this.mediaRecorder.ondataavailable = (event) => {
if (event.data && event.data.size > 0) {
this.recordedChunks.push(event.data);
}
};
// 开始录制
this.mediaRecorder.start();
this.isRecording = true;
console.log('开始录制...');
} catch (error) {
console.error('无法开始录制:', error);
}
},
async stopRecording() {
if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
this.mediaRecorder.stop();
this.isRecording = false;
console.log('录制结束');
// 将录制的数据块转换为Blob
const recordedBlob = new Blob(this.recordedChunks, {
type: 'video/mp4'
});
// 保存到本地
this.saveAsFile(recordedBlob, 'recorded-desktop-video.mp4');
}
},
saveAsFile(blob, fileName) {
// 创建隐藏的下载链接
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = fileName;
// 触发点击下载
document.body.appendChild(a);
a.click();
// 清理
setTimeout(() => {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 100);
},
}