我正尝试每5秒将视频片段添加到sourceBuffer,这在Firefox上效果很好,但在chrome上不行!
我发现在sourceBuffer updateend
之后,时间范围未在chrome!中更新,其长度仍为0。
但是在Firefox中,其长度更改为1。
我不知道是什么原因导致了这种行为。
这是我的代码:
var videoNumber = 1;
var video = document.querySelector('video');
var assetURL = '/classes/'+class_id+'/video/';
var segmentDuration = 5;
var duration = 5;
// Need to be specific for Blink regarding codecs
// ./mp4info frag_bunny.mp4 | grep Codec
var mimeCodec = 'video/webm; codecs="vp9, vorbis"';
var sourceBuffer;
var mediaSource;
if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) {
mediaSource = new MediaSource;
video.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener('sourceopen', sourceOpen);
} else {
console.error('Unsupported MIME type or codec: ', mimeCodec);
}
/**
* @desc start when video opened
* @param _
*/
function sourceOpen (_) {
console.log("source opened");
//console.log(this.readyState); // open
sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
appendSegmentIfExist();
video.addEventListener('timeupdate', checkBuffer);
sourceBuffer.addEventListener('updateend', playVideo);
}
var tries = 0;
function fetchVideo(videoNumber,callback = function (response) {
}) {
console.log("fetch video number "+ videoNumber);
var xhr = new XMLHttpRequest;
xhr.open('get', assetURL+videoNumber);
xhr.responseType = 'arraybuffer';
xhr.onloadend = function() {
if(xhr.status === 404)
{
console.log('tries is '+ tries);
if(tries > 3)
{
mediaSource.endOfStream();
return;
}
tries++;
fetchVideo(videoNumber,callback);
}
else
{
tries++;
callback(xhr.response);
}
};
xhr.send();
}
function appendSegment() {
fetchVideo(videoNumber,function(buf)
{
if(videoNumber === 1)
video.play().catch(function(e) {
console.log(e);
});
console.log(buf);
sourceBuffer.timestampOffset = duration - 5;
duration += 5;
sourceBuffer.appendBuffer(buf);
console.log(sourceBuffer);
});
}
function shouldFetchNextSegment () {
return video.currentTime > (segmentDuration*videoNumber - 1);
}
function checkBuffer () {
if (shouldFetchNextSegment()) {
console.log("should fetch next");
console.log('time to fetch next chunk', video.currentTime);
videoNumber++;
appendSegment();
}
}
function appendSegmentIfExist()
{
console.log("check if there is video on server ");
var xhr = new XMLHttpRequest;
xhr.open('get', assetURL+videoNumber);
xhr.responseType = 'arraybuffer';
xhr.onloadend = function() {
if(xhr.status === 404)
{
console.log('no video on server ');
}
else
{
appendSegment();
}
};
xhr.send();
}
function playVideo() {
console.log('update end');
console.log(sourceBuffer.buffered);
console.log(mediaSource.readyState);
mediaSource.duration = Infinity;
console.log(mediaSource.duration);
}
我尝试过sourceBuffer.addEventListener('error', logError);
,它返回了一个错误对象,同样,它只是在chrome上。