我如何从屏幕截图网站 API 存储/下载记录?

How can I store / download the recording from the Screen Capture web API?

我正在使用 Screen Capture API 并尝试将最终捕获保存到视频文件(WebM、MP4 等)。我有这两个 JavaScript 函数:

async function startCapture() {
    try {
      videoElem.srcObject = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
    } catch(err) {
      console.error("Error: " + err);
    }
}

function stopCapture() {
    let tracks = videoElem.srcObject.getTracks();
    tracks.forEach(track => track.stop());
    videoElem.srcObject = null;
}

捕获开始时,视频可以正常显示,但我不确定如何实际存储其内容。 videoElem 是解析为 MediaStreamPromisetracksMediaStreamTrack 个对象的数组。这是我第一次做任何类型的网络开发,所以我有点迷茫!

与任何 MediaStream 一样,您可以使用 MediaRecorder API.

记录它
MDN 文档上的

Recording a media element 对我帮助很大。基本上,我们不使用 getUserMedia(),而是使用 getDisplayMedia().

async function startRecording() {
    stream = await navigator.mediaDevices.getDisplayMedia({
      video: true,
      audio: true
});
recorder = new MediaRecorder(stream);

const chunks = [];
recorder.ondataavailable = e => chunks.push(e.data);
recorder.onstop = e => {
    const blob = new Blob(chunks, { type: chunks[0].type });
    console.log(blob);
    stream.getVideoTracks()[0].stop();

    filename="yourCustomFileName"
    if(window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveBlob(blob, filename);
    }
    else{
        var elem = window.document.createElement('a');
        elem.href = window.URL.createObjectURL(blob);
        elem.download = filename;        
        document.body.appendChild(elem);
        elem.click();        
        document.body.removeChild(elem);
    }
    };
    recorder.start();
}
startRecording(); //Start of the recording 

-----------

recorder.stop() // End your recording by emitting this event

这会将您的录音保存为 webm 文件