<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> </head> <body> <video controls></video> <script> var video = document.querySelector('video');
var assetURL = 'frag_bunny.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; var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec); 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); xhr.responseType = 'arraybuffer'; xhr.onload = function () { cb(xhr.response); }; xhr.send(); }; </script> </body> </html>
可以看到,其能力就是自定义请求媒体资源实现了加载,而自定义请求,则可以完全一些权限认证的操作。
mimeCodec
可以通过安装mp4box了解媒体文件的编码相关信息。
首先安装mp4box
1
brew install mp4box
通过mp4box -info xxx查看
因此有
1 2 3
var mimeCodec = 'video/mp4; codecs="avc1.640028, mp4a.40.2"'; ... var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> </head> <body> <video controls></video> <script> var video = document.querySelector('video');
var assetURL = 'frag_bunny.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"'; var totalSegments = 5; var segmentLength = 0; var segmentDuration = 0; var bytesFetched = 0; var requestedSegments = [];
for (var i = 0; i < totalSegments; ++i) requestedSegments[i] = false;
var mediaSource = null; if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) { 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); }
异常:InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer': This SourceBuffer has been removed from the parent media source. at SourceBuffer.invokeGetter