我正在尝试使用第一个演示 MediaSource 进行尝试,但我无法播放视频。我使用的来源是一个 webm 视频“big-buck-bunny_trailer.webm”。我不断收到“Uncaught InvalidStateError: Failed to perform 'endOfStream' on 'MediaSource': The 'updating' attribute is true on a or more this MediaSource's SourceBuffers.”。我也处理了 sourcebuffer 更新标志,但它似乎仍然不起作用。
window.URL = window.URL || window.webkitURL;
window.MediaSource = window.MediaSource || window.WebKitMediaSource;
if (!!!window.MediaSource) {
//handle fallback
alert('MediaSource API is not available');
}
var mediaSource = new MediaSource();
var sourceBuffer;
var audio;
var playRange = 0;
var queue = [];
var playing = false;
var contentLength = undefined;
function ajaxMediaGET(url, range, async, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "arraybuffer";
xhr.setRequestHeader("Range", range);
xhr.addEventListener('load', onLoad, false);
xhr.send();
function onLoad() {
playRange += Number(xhr.getResponseHeader("Content-Length"));
if(!contentLength) {
var contentLengthString = xhr.getResponseHeader("Content-Range").split("/");
contentLength = Number(contentLengthString[1]);
}
//callback(new Uint8Array(xhr.response));
sourceBuffer.addEventListener("update", function() {
if(!sourceBuffer.updating && queue.length > 0) {// && mediaSource.readyState == "open"
sourceBuffer.appendBuffer(queue.shift());
sourceBuffer.removeEventListener("update");
}
}, false);
if (!sourceBuffer.updating) {
sourceBuffer.appendBuffer(new Uint8Array(xhr.response));
} else {
queue.push(new Uint8Array(xhr.response));
}
if(playRange < contentLength - 1) {
ajaxMediaGET("path-to-server", loadNextRange(playRange), true, undefined);
} else {
mediaSource.endOfStream();
}
}
}
function mediaSourceOpen(e) {
sourceBuffer = e.target.addSourceBuffer('video/webm;codecs="vp8,vorbis"');
ajaxMediaGET("path-to-server", loadNextRange(playRange), true, undefined);
/*if(!playing) {
audio.play();
playing = true;
}*/
}
function initPlayer() {
audio = document.querySelector('video');
audio.src = window.URL.createObjectURL(mediaSource);
mediaSource.addEventListener('sourceopen', mediaSourceOpen, false);
mediaSource.addEventListener('webkitsourceopen', mediaSourceOpen, false);
}
initPlayer();