Cristobal Bahe
Cristobal Bahe

Reputation: 21

Is it possible to re-use the same blob url from createObjectURL of a MediaSource?

I am trying to get a media source as the src of multiple videos but whenever I try to set the blob url generated by createObjectUrl, I get an error ERR_FILE_NOT_FOUND on the second video I try to set the src on. For now to achieve what I am trying to do I have to create a new MediaSource for each video I want to use the src on.

What I am trying to do is to have a number of videos that play my webcam feed with a delay each one greater than the previous (so the first video is the live webcam, the first video has a delay of 200ms, the second one has a delay of 400ms and so on).

So what I am doing is create a MediaRecorder that everytime it receives data (every 100ms) it appends that data to a sourceBuffer of each of the media sources that it's the src of each video. So whenever I play that video with a setTimeout it shows the original video with delay.

So the ideal would be to use a single MediaSource as the src of all the videos since the information is the same and I am just appending the same information to different source buffers.

Here is my code for now:

   navigator.mediaDevices
  .getUserMedia({
    video: true
  })
  .then((stream) => {

    const mimeType = `video/webm; codecs="vp8"`;
    const delay = 500;

    const webcamVideo = document.createElement("video");
    webcamVideo.autoplay = true;
    webcamVideo.srcObject = stream;

    webcamVideo.addEventListener("loadeddata", () => {

      const recorder = new MediaRecorder(webcamVideo.captureStream(), { mimeType });
      const sourceBuffers = [];
      recorder.ondataavailable = async ({ data }) => {
        sourceBuffers.forEach(async (sourceBuffer) => {
          sourceBuffer.appendBuffer(await data.arrayBuffer());
        });
      };
      const numberOfReplicas = 4;
      for (let i = 0; i < numberOfReplicas; i++) {
        const mediaSource = new MediaSource();
        const video = document.createElement("video");
        video.autoplay = true;
        document.body.appendChild(video);
        const src = URL.createObjectURL(mediaSource);
        video.src = src;
        

        mediaSource.addEventListener(
          "sourceopen",
          () => {
            const sourceBuffer = mediaSource.addSourceBuffer(mimeType);
            sourceBuffers.push(sourceBuffer);

            video.pause();

            setTimeout(() => {
              video.play();
            }, delay * (i + 1));
          },
          { once: true }
        );
      }
      recorder.start(200);
    });
  });

Here is a codepen just in case: https://codepen.io/cristobalbahe/pen/WNYEPjY

I hope I am making myself clear!

Thank you everyone very much in advance.

Upvotes: 1

Views: 288

Answers (0)

Related Questions