0
点赞
收藏
分享

微信扫一扫

ICode国际青少年编程竞赛- Python-1级训练场-for循环与变量

  在做之前,以为DPlaye知道数据流,录像直接保存即可。结果是,根本没有录像功能。

  怎么办呢?搜索了一番,给出的建议是使用Canvas加MediaRecorder来实现。大意是使用canvas,定时把视频画面刷过来;然后MediaRecorder对canvas进行录像。目前是唯一知道可行方案。

  其实我也觉得这个办法比较愚蠢或者原始。目前并没有找到别的办法,所以只能如此。其实这些代码也都是参考别人的,我也是略微整理,确认确实可以实现录像功能。

  • 代码1:声明
export default {
  name: "flvPlayer",
  data() {
    return {
      dp: null,

      isRecording: false,
      refreshTimer: 0,
      canvas: null,
      context : null,
      mediaRecorder: null,
      recordedBlobs: [],
    }
  },
  • 代码2:recordAction
recordAction() {
    this.isRecording = !this.isRecording;
    if (this.isRecording) {
        this.startRecording();
    }
    else {
        this.stopRecording();
        this.downloadVideo();
    }
},
  • 代码3:startRecording
    //this.dp = new DPlayer(options);

    startRecording() {
        const FPS      = 25;
        const INTERVAL = 1000/FPS;

        this.canvas        = document.createElement('canvas');
        this.context       = this.canvas.getContext('2d');
        this.canvas.width  = this.dp.video.videoWidth;
        this.canvas.height = this.dp.video.videoHeight;

        this.stream = this.canvas.captureStream(FPS);
        
        this.refreshTimer = setInterval(() => {
            this.context.drawImage(this.dp.video, 0, 0, this.canvas.width, this.canvas.height);
        }, INTERVAL);
    
        this.mediaRecorder = new MediaRecorder(this.stream,
             { mimeType: 'video/webm;codecs=h264'});

        this.recordedBlobs = [];
        this.mediaRecorder.ondataavailable = (event) => {
            if (event.data && event.data.size > 0) {
              this.recordedBlobs.push(event.data);
            }
        };
        this.mediaRecorder.onerror = (error) => {
            console.log("onerror() "+error);
        };
        this.mediaRecorder.onstop = () => {
            console.log("onstop()");
        };
        this.mediaRecorder.start(INTERVAL);
    },
  • 代码4:stopRecording()
    stopRecording() {
      if (!this.mediaRecorder) {
        return;
      }
      this.mediaRecorder.stop();
      this.mediaRecorder = null;

      clearInterval(this.refreshTimer);
      this.refreshTimer = 0;
    },
  • 代码5:downloadVideo
    downloadVideo() {
      const superBuffer = new Blob(this.recordedBlobs, { type: 'video/webm' });
      // 使用URL.createObjectURL() 创建一个URL
      const url = URL.createObjectURL(superBuffer);
      downloadUrl(url, "mp4");
      this.recordedBlobs = [];
    },
  • 代码6:donwloadUrl

VUE自动下载代码,指定文件名-CSDN博客

举报

相关推荐

0 条评论