尝试使用MSE(媒体来源扩展)播放视频。我能够在Ajax响应中获得块并附加到sourceBuffer,但是在播放时它不能播放。这是我写的示例代码......
function playMedia(src) {
var BasicPlayer = function () {
var self = this;
this.initiate = function (sourceFile) {
if (!window.MediaSource || !MediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E, mp4a.40.2"')) {
self.setState("Your browser is not supported");
return;
}
self.clearUp();
self.sourceFile = sourceFile;
self.videoElement = VIDEO;
self.mediaSource = new MediaSource();
self.mediaSource.addEventListener('sourceopen', function () {
self.createSourceBuffer();
}, false);
//append the video element to the DOM
self.videoElement.src = window.URL.createObjectURL(self.mediaSource);
self.videoElement.pause();
$('#basic-player').append($(self.videoElement));
}
this.clearUp = function() {
if (self.videoElement) {
//clear down any resources from the previous video embed if it exists
$(self.videoElement).remove();
delete self.mediaSource;
delete self.sourceBuffer;
}
}
this.setState = function (state) {
alert(state);
}
this.createSourceBuffer = function () {
self.sourceBuffer = self.mediaSource.addSourceBuffer('video/mp4');
self.sourceBuffer.addEventListener('updateend', function () {
self.setState("Ready");
self.videoElement.play();
}, false);
var xhr = new XMLHttpRequest();
xhr.open('GET', self.sourceFile, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function (e) {
if (xhr.status !== 200) {
self.setState("Failed to download video data");
self.clearUp();
} else {
alert("chunk received...");
if(xhr!=null && xhr.response!=null){
var arr = new Uint8Array(xhr.response);
if (!self.sourceBuffer.updating) {
self.setState("Appending video data to buffer");
self.sourceBuffer.appendBuffer(arr);
alert(self.sourceBuffer);
} else {
self.setState("Source Buffer failed to update");
}
}else{
self.setState(xhr.response+"");
}
}
};
xhr.onerror = function () {
self.setState("Failed to download video data");
self.clearUp();
};
xhr.send();
self.setState("Downloading video data");
}
}
var basicPlayer = new BasicPlayer();
window.updatePlayer = function (sourceFile) {
basicPlayer.initiate(sourceFile);
}
updatePlayer(src);
}