实现web端录屏功能(录屏+录音)

前言:满满的干货,简单快速高效的实现录屏录音的功能。实现需求:在一个管理系统中添加一个录屏讲解功能,有开始录屏,暂停录屏,停止录屏,录屏下载本地,录屏上传到阿里云服务器等。用得到技术:vue+recordrtc
这篇文章基本上能满足所有录屏的需求,如果开发中遇到问题欢迎私信我

recordrtc 安装

npm install recordrtc --save

使用

import RecordRTC from 'recordrtc';

代码

//开始录制
startR() {
      this.startRecording((start) => {
        this.start = start;
      });
 },
 startRecording(callback) {
      if (this.startTxt === '开始录制') { 
        this.captureScreen((screenStream) => {
          this.addStreamStopListener(screenStream, () => {
            console.log("流停止监听");
            // this.$emit("streamStop", {})
            this.stopR();
          });
          this.isPause = true
          this.startTxt = '停止录制'
          var options = {
            type: 'video',
            mimeType: 'video/mp4',
            disableLogs: false,
            getNativeBlob: false, // enable it for longer recordings
            ignoreMutedMedia: false
          };
          this.recorder = RecordRTC(screenStream, options);
          this.recorder.startRecording();
          this.recorder.screen = screenStream;
          this.videoStart = true;
          callback(true);
        });
      } else if (this.startTxt === '停止录制') {
        this.stopR()
      }

    },
 /**
   * 停止录制
 */
 stopR() {
      this.startTxt = '开始录制'
      this.isPause = false
      this.stopRecording((start) => {
        this.start = start;
      });
    },
    /**
     * 停止录制回调
     */
    stopRecording(callback) {
      this.recorder.stopRecording(() => {
        // 设置录屏资料的文件名称为当前时间,以保证每次录屏资料名称的唯一性(当然也可以用随机数设置,这个可以根据自己的需要设置)
        let mydate = new Date()
        let myyear = mydate.getFullYear(); //获取完整的年份(4位,1970-????)
        let mymonth = mydate.getMonth() + 1; //获取当前月份(0-11,0代表1月)
        let mytoday = mydate.getDate(); //获取当前日(1-31)
        let myhour = mydate.getHours(); //获取当前小时数(0-23)
        let myminute = mydate.getMinutes(); //获取当前分钟数(0-59)
        let mysecond = mydate.getSeconds(); //获取当前秒数(0-59)
        this.fileName = `${myyear}` + `${mymonth}` + `${mytoday}` + `${myhour}` + `${myminute}` + `${mysecond}`
        const url = URL.createObjectURL(this.recorder.getBlob());
        this.aTag = document.createElement("a");
        let videoFile = new File([this.recorder.getBlob()], this.fileName + ".mp4", {
          type: 'video/mp4'
        })
        let downloadUrl = URL.createObjectURL(videoFile);
        document.body.appendChild(this.aTag);
        this.aTag.style.display = "none";
        this.aTag.href = url;
        this.videoFile = videoFile
        this.viewFn()
        // this.uploadHttp({ file: this.videoFile })
        this.previewVideo = downloadUrl
        // 停止录屏时同时下载到本地 
        // this.aTag .download = this.fileName + ".mp4";
        // this.aTag .click();
        this.recorder.screen.stop();
        this.recorder.destroy();
        this.recorder = null;
        this.videoStart = false;
        this.$message({
          message: '录屏停止',
          type: 'success'
        })
        callback(false);
      });
    },
 pauseFn() {
      if (this.pauseTxt === "暂停") {
        this.$message({
          message: '录屏已暂停',
          type: 'success'
        })
        this.recorder.pauseRecording()
        this.pauseTxt = "恢复录制"
      } else if (this.pauseTxt === "恢复录制") {
        this.$message({
          message: '录屏已恢复',
          type: 'success'
        })
        this.recorder.resumeRecording()
        this.pauseTxt = "暂停"
      }

    },
//初始化录制
captureScreen(callback) {
      if (navigator.getDisplayMedia) {
        //录制结束,文件下载
        navigator.getDisplayMedia({
          video: true, audio: true
        }).then(screenStream => {
          navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then((mic) => {
            screenStream.addTrack(mic.getTracks()[0]);
            callback(screenStream);
          });
        }).catch(function (error) {
          console.log('error', error);
        });
      } else if (navigator.mediaDevices.getDisplayMedia) {
        navigator.mediaDevices.getDisplayMedia({
          video: true, audio: true
        }).then(screenStream => {
          navigator.mediaDevices.getUserMedia({ audio: true }).then((mic) => {
            screenStream.addTrack(mic.getTracks()[0]);
            callback(screenStream);
          });
        }).catch(function (error) {
          console.log('error', error);
        });
      } else {
        var error = 'getDisplayMedia API are not supported in this browser.';
        console.log('error', error);
        alert(error);
      }
    },
//流监听
addStreamStopListener(stream, callback) {
      stream.addEventListener('ended', function () {
        callback();
        callback = function () { };
      }, false);
      stream.addEventListener('inactive', function () {
        callback();
        callback = function () { };
      }, false);
      stream.getTracks().forEach(function (track) {
        track.addEventListener('ended', function () {
          callback();
          callback = function () { };
        }, false);
        track.addEventListener('inactive', function () {
          callback();
          callback = function () { };
        }, false);
      });
    },

注:视频上传到阿里云这块代码没有贴,可以直接去阿里云官方网站粘贴代码

recordrtc参考链接

你可能感兴趣的:(实现web端录屏功能(录屏+录音))