vue 调用pc端本地设备录制

226 阅读1分钟

概括

  • 这个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' });

        // 处理或保存录制的 Blob 数据
        console.log('录制完成,数据处理或保存:', recordedBlob);

        // 清空录制的数据
        this.recordedChunks = [];
      }
    },
  },
};
</script>

展示效果

WechatIMG423.jpg