2011-12-25 37 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(); 
    } 
}; 

對於視頻的「預加載」屬性還值「自動」,不保證用戶代理將加載整個視頻。