0

我正在尝试构建一个简单的屏幕录像机,并且在 MDN 文档的帮助下,我具有以下两个功能:

window.onload = function startStream() {
    navigator.mediaDevices.getDisplayMedia({
        video: {
            cursor: "always"
        },
        audio: true
    }).then(stream => {
        preview.srcObject = stream;
        downloadButton.href = stream;
        preview.captureStream = preview.captureStream || preview.mozCaptureStream;
        return new Promise(resolve => preview.onplaying = resolve);
    }).then(() => startRecording(preview.captureStream())).then(recordedChunks => {
        let recordedBlob = new Blob(recordedChunks, {
            type: "video/webm"
        });
        recording.src = URL.createObjectURL(recordedBlob);
        downloadButton.href = recording.src;
        downloadButton.download = "RecordedVideo.webm";
    });
}

async function startRecording(stream) {
    let recorder = new MediaRecorder(stream);
    let data = [];

    recorder.ondataavailable = event => data.push(event.data);
    recorder.start();

    let stopped = new Promise((resolve, reject) => {
        recorder.onstop = resolve;
        recorder.onerror = event => reject(event.name);
    });
  
    let recorded = () => recorder.state == "recording" && recorder.stop();
    
    await Promise.all([stopped, recorded]);
    return data;
}

我想在数据开始记录之前添加一个延迟(比如 3 秒)。我试着在不同的地方玩,setTimeout()但一直Cannot GET /[object%20MediaStream]出错。任何帮助都是极好的!

4

1 回答 1

0

Ciao,试着做这样的事情:

function wait() {
   return new Promise(resolve => {
   setTimeout(() => {
   resolve();
 }, 3000);
});
}

async function startRecording(stream) {
   let recorder = new MediaRecorder(stream);
   let data = [];

   recorder.ondataavailable = event => data.push(event.data);
   await wait(); 
   recorder.start();

   let stopped = new Promise((resolve, reject) => {
       recorder.onstop = resolve;
       recorder.onerror = event => reject(event.name);
   });

   let recorded = () => recorder.state == "recording" && recorder.stop();

   await Promise.all([stopped, recorded]);
   return data;
}
于 2020-07-22T00:02:10.003 回答