2011-12-25 70 views
1

我有以下函数来计算视频的加载进度(很常见):HTML5视频下载进度仅工作在Firefox

function updateProgressBar (video) { 
    if (video.buffered.length > 0) { 
     var percent = (video.buffered.end(0)/video.duration) * 100; 
     $('#loading').css({'width': percent + '%'}); 
     console.log(percent); 
     if (percent == 100) { 
      console.log('video loaded!'); 
      //everything is loaded, do something. 
      $(video).unbind('loadeddata canplaythrough playing'); //prevents the repetition of the callback 
     } 
    }   
} 

...绑定到“进步”事件(和一些其他的安全meassure)一个$(document).ready函数内:

var videoTest = document.getElementById("videoTest"); 

$('#videoTest').bind('progress', function() { 
    updateProgressBar (videoTest); 
}); 

$('#videoTest').bind('loadeddata', function() { 
    updateProgressBar (videoTest); 
}); 

$('#videoTest').bind('canplaythrough', function() { 
    updateProgressBar (videoTest); 
}); 

$('#videoTest').bind('playing', function() { 
    updateProgressBar (videoTest); 
}); 

您可以查看这里活生生的例子:http://www.hidden-workshop.com/video/

正如你所看到的,它在Firefox上运行得很好,但在其他浏览器中,'百分比'变量永远达不到'100'的值,因为它是预期的;该功能总是停在90〜,因此我无法知道视频何时完成加载(对于我所要做的事情至关重要)。

就像'progress'事件在我能够获得'percent'的最终值之前停止工作,因为如果您点击'play'按钮,'playing'事件触发,然后成功计算并读取'percent' '变量的最后一个值(它是100)。

我错过了什么,或者它是一个常见问题?有没有可以使用的解决方法?

在此先感谢!

回答

0
var videoElement = null; //TODO set reference to video element 

var checkVideoLoadingProgressTimerDelay = 50; 
var checkVideoLoadingProgressTimerID = -1; 

function getVideoLoadingProgress(){ 
    var end = 0; 
    if(videoElement.buffered.length >= 1){ 
     end = videoElement.buffered.end(0); 
    } 
    var progress = end/videoElement.duration; 
    progress = isNaN(progress) ? 0 : progress; 
    return progress; 
}; 

function startCheckVideoLoadingProgressTimer(){ 
    checkVideoLoadingProgressTimerID = 
     setTimeout(checkVideoLoadingProgressTimerHandler, checkVideoLoadingProgressTimerDelay); 
}; 

function checkVideoLoadingProgressTimerHandler(){ 
    var progress = getVideoLoadingProgress(); 
    //TODO update progress bar 
    if(progress < 1){ 
     startCheckVideoLoadingProgressTimer(); 
    } 
}; 

对于视频的“预加载”属性还值“自动”,不保证用户代理将加载整个视频。