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

810 Views Asked by At

I'm trying to build a simple screen recorder, and, with the help of the MDN docs, I have the following two functions:

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

I want to add a delay before the data starts recording (like 3 seconds). I tried playing around with setTimeout() in different spots but kept on getting a Cannot GET /[object%20MediaStream] error. Any help would be awesome!

1

There are 1 best solutions below

1
On BEST ANSWER

Ciao, try to do something like this:

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