如何在开始录制 MediaStream 之前添加延迟?

How can I add a delay before starting to record a MediaStream?

我正在尝试构建一个简单的屏幕录像机,并且在 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] 错误。任何帮助都会很棒!

再见,试着做这样的事情:

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;
}