Domanda

So I have a downloading .mp4 file. I would like to stream the download file into a video element using the MediaSource API. How would I do this?

const NUM_CHUNKS = 5;

var video = document.querySelector('video');
video.src = video.webkitMediaSourceURL;

video.addEventListener('webkitsourceopen', function(e) {
  var chunkSize = Math.ceil(file.size / NUM_CHUNKS);

  // Slice the video into NUM_CHUNKS and append each to the media element.
  for (var i = 0; i < NUM_CHUNKS; ++i) {
    var startByte = chunkSize * i;

    // file is a video file.
    var chunk = file.slice(startByte, startByte + chunkSize);

    var reader = new FileReader();
    reader.onload = (function(idx) {
      return function(e) {
    video.webkitSourceAppend(new Uint8Array(e.target.result));
    logger.log('appending chunk:' + idx);
    if (idx == NUM_CHUNKS - 1) {
      video.webkitSourceEndOfStream(HTMLMediaElement.EOS_NO_ERROR);
    }
      };
    })(i);

    reader.readAsArrayBuffer(chunk);
  }
}, false);

How would I dynamically change the NUM_CHUNKS,and slice the video?

È stato utile?

Soluzione

The code you're using from Eric Bidelman chops up a video that the browser already fully downloaded to demonstrate how the api works. In reality, you'd slice the video on the server, and the client would download each chunk in order, probably with an AJAX request.

I'd first suggest you try your .mp4 in the demo code you have, because MediaSource seems pretty picky about the format of the video files it accepts. See Steven Robertson's answer about how to create an mp4 that'll work.

Then it's up to you whether you want to slice the video manually beforehand, or do it dynamically on the server (which will vary depending on your server). The javascript client shouldn't care how many or how large each chunk each is, as long as they're fed in order (and I think the spec even allows some amount of out-of-order appending).

Altri suggerimenti

webkitMediaSourceURL; is now outdated in Chrome, and now createObjectURL(); needs to be used.

The patch here: HTMLMediaElement to the new OO MediaSource API gave me some pointers as to what I needed to update in my code.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top