概括
- 这个Vue组件会显示一个视频预览框和开始/停止录制的按钮。
- 当用户点击开始录制按钮时,它将开始录制视频。
- 当用户点击停止录制按钮时,它将停止录制并保存录制的视频。
示例用法
<template>
<div>
<button @click="startRecording" :disabled="recording">开始录制</button>
<button @click="stopRecording" :disabled="!recording">停止录制</button>
<video ref="videoElement" autoplay></video>
</div>
</template>
<script>
export default {
data() {
return {
mediaRecorder: null,
mediaStream: null,
recordedChunks: [],
recording: false,
};
},
mounted() {
this.videoElement = this.$refs.videoElement;
},
methods: {
startRecording() {
navigator.mediaDevices
.getUserMedia({ audio: true, video: true })
.then(stream => {
this.mediaStream = stream;
this.mediaRecorder = new MediaRecorder(stream);
this.mediaRecorder.ondataavailable = event => {
if (event.data.size > 0) {
this.recordedChunks.push(event.data);
}
};
this.mediaRecorder.start();
this.recording = true;
this.videoElement.srcObject = stream;
})
.catch(error => {
console.error('无法启动录制:', error);
});
},
stopRecording() {
if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
this.mediaRecorder.stop();
this.recording = false;
this.mediaStream.getTracks().forEach(track => track.stop());
this.processRecordedData();
}
},
processRecordedData() {
if (this.recordedChunks.length > 0) {
const recordedBlob = new Blob(this.recordedChunks, { type: 'video/webm' });
console.log('录制完成,数据处理或保存:', recordedBlob);
this.recordedChunks = [];
}
},
},
};
</script>
展示效果
