Steaming a growing file using the MediaSource API.

南楼画角 提交于 2019-12-21 06:55:41

问题


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?


回答1:


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).




回答2:


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.



来源:https://stackoverflow.com/questions/19546994/steaming-a-growing-file-using-the-mediasource-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!