工作生活

Js 录制屏幕

2019-07-02  本文已影响0人  1缥缈的云1

最新的Js录制屏幕主要通过getDisplayMedia({video:true, audio:true})来实现。audio:true表示要录制背景音。目前仅最新的chrome录制tab时支持。效果如下图:


风景

index.html 如下:

<!DOCTYPE html>

<html>

<head> 

<meta charset="utf-8"> 

<title>JS教程(https://www.jianshu.com/u/0099dbb879da)</title> 

</head>

<body>

<video id= "video" width="320" height="240" controls autoplay src="https://www.runoob.com/try/demo_source/movie.mp4">

    <object data="movie.mp4" width="320" height="240">

    <embed width="320" height="240" src="movie.swf">

  </object>

</video>

<button type="button" onclick="recordScreen()">Start</button>

<script src='index.js'></script>

<script>

function recordScreen(){

var recorder = new Recorder("test.mp4");

recorder.startRecord();

let t = setTimeout(function(){

recorder.stopRecord();

clearTimeout(t);

},10000)

}

</script>

</body>

</html>

index.js如下:

/**

*自动录屏模块*录制桌面

*

* @class Recorder

*/

class Recorder {

  constructor(path) {

    this.mediaOutputPath = path;

  }

  /**

  *开始录制

  *

  * @memberof Recorder

  */

  startRecord (){

    navigator.mediaDevices.getDisplayMedia({video:true, audio:true}).then(Mediastream => {

        this.createRecorder(Mediastream);



      }).catch(err => {

        this.getUserMediaError(err);

      })

  }

  /**

  *获取媒体源失败

  *

  * @memberof Recorder

  */

  getUserMediaError(err){

    console.log('mediaError',err);

  }

  /**

  *开始视频录制

  *

  * @memberof Recorder

  */

  createRecorder(stream){

    console.log('start record');

    this.recorder = new MediaRecorder(stream);

    this.recorder.start();

    var chunks = [];

    this.recorder.onstop = event => {

      let blob = new Blob(chunks, {

        type: 'video/mp4'

      });

      this.saveMedia(blob);

    }

    this.recorder.ondataavailable = event => {

      chunks.push(event.data);

    };

  }

  /**

  *数据转换并保存成MP4

  *

  * @memberof Recorder

  */

  saveMedia(blob){

    let url = window.URL.createObjectURL(blob);

    var video = document.getElementById("video");

    video.src = url;



    // var a = document.createElement('a');

    // a.innerHTML = "test";

    // a.download = "test.mp4";

    // a.href = url;

    // document.body.appendChild(a);





  }

  /**

  *停止录制视频

  *

  * @memberof Recorder

  */

  stopRecord(){

    this.recorder.stop();

  }

}
上一篇下一篇

猜你喜欢

热点阅读