乐趣区

关于javascript:js实现屏幕录制并保存视频

用到的相干 API

  1. revokeObjectURL()、URL.createObjectURL()
  2. avigator.mediaDevices.getDisplayMedia()
  3. new MediaRecorder()

    页面布局

  4. video 和三个按钮(start,stop,download)
  5. 别离点击对应三个事件,startCapture(),stopCapture(),mydownload()

    实现

  6. 保留录制生成的视频能够借助 Blob 转换成二进制,而后,作为 a 元素的 href 属性,配合 download 属性,实现下载。

    代码如下

    https://gitee.com/liu_qiao_xu…

const video = document.getElementById('video');
const start = document.getElementById('start');
const stop = document.getElementById('stop');
const download = document.getElementById('download');


const displayMediaOptions = {
    video: {cursor: "never"},
    audio: true
}

start.addEventListener('click',function(evt){startCapture();
},false)

stop.addEventListener('click',function(evt){stopCapture();
},false)

download.addEventListener('click',function(evt){mydownload();
},false)


let captureStream;
let recorder;
async function startCapture() {
    log = "";
    try {captureStream = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
    } catch (err) {console.log('Error:' + err);
        return alert('capture is error or cancel!');
    }
    // 删除原来的 blob
    window.URL.revokeObjectURL(video.src);
    video.srcObject = captureStream;
    recorder = new MediaRecorder(captureStream);
    recorder.start();}

function stopCapture() {let tracks = video.srcObject.getTracks();
    tracks.forEach(track => {track.stop();
    });
    recorder.stop();
    recorder.addEventListener('dataavailable',(event)=>{let videoUrl = URL.createObjectURL(event.data,{type:'video/mp4'});
        video.srcObject = null;
        video.src = videoUrl;
    })

}

function mydownload(){const name = new Date().toISOString().slice(0,19).replace('T','').replace(' ','_').replace(/:/g,'-');
    const a = document.createElement('a');
    a.href = video.src;
    a.download = `${name}.mp4`;
    document.body.appendChild(a);
    a.click();}

后果

退出移动版