Javascript mediaSource元素

时间:2016-09-23 09:02:01

标签: javascript html

我正在尝试使用javascript mediasource播放视频,以隐藏用户的视频网址。但我得到一个错误,

未捕获的InvalidStateError:无法执行' endOfStream'在' MediaSource':MediaSource的readyState没有打开'。如果要动态传递视频类型和代码也会有所帮助。

以下是我的代码,

<!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>

1 个答案:

答案 0 :(得分:1)

上述代码不起作用的原因是,只有在开头移动的带有moov(电影标题框)的碎片mp4视频将使用媒体源播放。

参考以下链接, 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?

您可以使用MP4box工具使用以下命令

对视频进行分段

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