Shuj
Shuj

Reputation: 31

JavaScript: Use MediaRecorder to record streams from <video> but failed

I'm trying to record parts of the video from a tag, save it for later use. And I found this article: Recording a media element, which described a method by first calling stream = video.captureStream(), then use new MediaRecord(stream) to get a recorder.

I've tested on some demos, the MediaRecorder works fine if stream is from user's device (such as microphone). However, when it comes to media element, my FireFox browser throws an exception: MediaRecorder.start: The MediaStream's isolation properties disallow access from MediaRecorder.

So any idea on how to deal with it?

Browser: Firefox

The page (including the js file) is stored at local.

The src attribute of <video> tag could either be a file from local storage or a url from Internet.

Code snippets:

let chunks = [];

let getCaptureStream = function () {
    let stream;
    const fps = 0;
    if (video.captureStream) {
      console.log("use captureStream");
      stream = video.captureStream(fps);
    } else if (video.mozCaptureStream) {
        console.log("use mozCaptureStream");
      stream = video.mozCaptureStream(fps);
    } else {
      console.error('Stream capture is not supported');
      stream = null;
    }
    return stream;
}

video.addEventListener('play', () => {
    let stream = getCaptureStream();
    const mediaRecorder = new MediaRecorder(stream);
    mediaRecorder.onstop = function() {
        const newVideo = document.createElement('video');
        newVideo.setAttribute('controls', '');
        newVideo.controls = true;
        const blob = new Blob(chunks);
        chunks = [];
        const videoURL = window.URL.createObjectURL(blob, { 'type' : 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"' });
        newVideo.src = videoURL;
        document.body.appendChild(video);
    }
    mediaRecorder.ondataavailable = function(e) {
        chunks.push(e.data);
      }
      
    stopButton.onclick = function() {
        mediaRecorder.stop()
    }

    mediaRecorder.start(); // This is the line triggers exception.
  });

Upvotes: 2

Views: 877

Answers (1)

Shuj
Shuj

Reputation: 31

I found the solution myself.

When I turned to Chrome, it shows that a CORS issue limits me from even playing original video. So I guess it's because the secure strategy that preventing MediaRecorder from accessing MediaStreams. Therefore, I deployed the local files to a local server with instruction on this page. After that, the MediaRecorder started working. Hope this will help someone in need.

But still, the official document doesn't seem to mention much about isolation properties of media elements. So any idea or further explanation is welcomed.

Upvotes: 1

Related Questions