Js 錄制屏幕

最新的Js錄制屏幕主要通過getDisplayMedia({video:true, audio:true})來實(shí)現(xiàn)。audio:true表示要錄制背景音。目前僅最新的chrome錄制tab時(shí)支持。效果如下圖:


風(fēng)景

index.html 如下:

<!DOCTYPE html>

<html>

<head> 

<meta charset="utf-8"> 

<title>JS教程(http://m.itdecent.cn/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如下:

/**

*自動(dòng)錄屏模塊*錄制桌面

*

* @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);

    };

  }

  /**

  *數(shù)據(jù)轉(zhuǎn)換并保存成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();

  }

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容