3

I am trying to play a video using javascript mediasource to hide video URL from the users. But I get an error as,

Uncaught InvalidStateError: Failed to execute 'endOfStream' on 'MediaSource': The MediaSource's readyState is not 'open'. And it would also be helpful if the video type and codes to be passed dynamically.

Below is my code,

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8"/>
  </head>
  <body>
    <video controls></video>
<script>
  var video = document.querySelector('video');

  var assetURL = 'adsss.mp4';
  // Need to be specific for Blink regarding codecs
  // ./mp4info frag_bunny.mp4 | grep Codec
  var mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';

  if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) {
    var mediaSource = new MediaSource;
    //console.log(mediaSource.readyState); // closed
    video.src = URL.createObjectURL(mediaSource);
    mediaSource.addEventListener('sourceopen', sourceOpen);
  } else {
    console.error('Unsupported MIME type or codec: ', mimeCodec);
  }

  function sourceOpen (_) {
    console.log(this.readyState); // open
    var mediaSource = this;
    console.log(mediaSource);
    var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
    console.log(sourceBuffer);
    fetchAB(assetURL, function (buf) {
      sourceBuffer.addEventListener('updateend', function (_) {
        mediaSource.endOfStream();
        video.play();
        console.log(mediaSource.readyState); // ended
      });
      sourceBuffer.appendBuffer(buf);
    });
  };

  function fetchAB (url, cb) {
    console.log(url);
    var xhr = new XMLHttpRequest;
    xhr.open('get', url);
    console.log(xhr);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function () {
      cb(xhr.response);
      console.log(xhr.response);
    };
    xhr.send();
  };
</script>

Zoran Pandovski
  • 2,312
  • 14
  • 24
Priyadarshni
  • 184
  • 1
  • 13

1 Answers1

1

The reason why the above code was not working is that, only fragmented mp4 videos with moov(movie header box) moved at the beginning will be played using the Media source.

Refer the below links, 1) Unable to get MediaSource working with mp4 format in chrome 2) What exactly is Fragmented mp4(fMP4)? How is it different from normal mp4?

You can fragment your videos using MP4box tool with the following command,

MP4Box -dash 1000 -rap -frag-rap test.mp4

Community
  • 1
  • 1
Priyadarshni
  • 184
  • 1
  • 13
  • I had same issue and one of my video worked but not the other. The other video was recorded using iphone and is in .mp4 format. Can you please help what can be the issue. – Sukhwinder Sodhi Aug 09 '19 at 13:04