2014-01-22 59 views
6

我有一個使用<video loop="true">的循環HTML5視頻,我想知道視頻何時循環。事件監聽器play僅在視頻最初啓動時觸發,並且ended不會觸發。當HTML5 <video>循環重新啓動時,用Javascript檢測?

timeupdate的不精確性使我很緊張,使用if (v.currentTime <= 0),但它似乎工作。有沒有更好的方法來檢測視頻何時重新啓動?

這是我的基本設置:

<video autoplay="true" loop="true" muted="true"> 
<source src="vidoe.mp4" type="video/mp4"> 
<source src="video.webm" type="video/webm"> 
<source src="video.ogv" type="video/ogg"> 
</video> 
<div id="Video-Time"></div> 

<script> 
var v = document.getElementsByTagName('video')[0] 
var t = document.getElementById('Video-Time'); 

v.addEventListener('timeupdate',function(event){ 
    t.innerHTML = v.currentTime; 
    if (v.currentTime <= 0) { console.log("Beginning!"); } // It does trigger when looping, surprisingly 
},false); 
v.addEventListener('play', function() { 
    console.log("play!"); // Only triggered when the video initially starts playing, not when the loop restarts 
},false); 
v.addEventListener('ended', function() { 
    console.log("ended!"); // Never triggered 
},false); 
</script> 
+2

的'seeked'事件應該火,但如果你對視頻控制視頻時,用戶seeked以及它會火。 – adeneo

+0

減少用戶清理的影響我可能會設置一個標誌,當currentTime達到視頻的最後一秒,然後如果有一個成功的尋求currentTime 0假設循環已觸發 – Offbeatmammal

回答

7

我認爲最可靠的方法是自己循環。取出loop屬性,並做到這一點:

document.querySelector('video').addEventListener('ended', function() { 
 
    console.count('loop restart'); 
 
    this.play(); 
 
})
<video autoplay muted src="https://rawgit.com/bower-media-samples/big-buck-bunny-480p-5s/master/video.mp4"></video>

0

我不知道這種方法是如何健壯,但東西我已經通過

player.on("timeupdate", function(e) { 
    console.log(player.currentTime) 
}); 

發現的是,如果用戶磨砂爲0的時候, timeupdate事件使用currentTime==0觸發兩次,如果視頻循環觸發,則使用currentTime==0觸發timeupdate三次。這似乎在FF,Chrome,IE中都存在,但我不知道它是與規範的通用實現還是硬件相關。即快速機器3滴答,慢機器5滴答currentTime==0

還有player.played將返回範圍播放的TimeRanges對象。所以:

player.on("timeupdate", function(e) { 
    var tr = player.played; 
    var hasLoopedOnce = (tr.end(tr.length-1)==player.duration); 
    console.log(hasLoopedOnce); 
}); 

這個問題是,範圍不會在每次迭代後重置,因此它僅適用於檢測第一個循環。我試過player.played = null但無濟於事。

但是如果確實只是player.currentTime <=0是不夠的,但使用這些方法來設置標誌並結合player.currentTime <=0可能已足夠用於某些情況。

5

我不得不爲移動做到這一點。您無法在移動設備上接受答案,因爲移動設備需要用戶互動才能再次運行play()(在很多情況下,尤其是在大多數網絡視圖中)

「timeupdate」中唯一可以依賴的是currentTime==0。由於我們知道currentTime==0將在「timeupdate」2-7次運行,具體取決於hardware/whatever,我們可以設置一個布爾值,以便在條件滿足後立即將布爾值設置爲false,然後開啓我們可以重置布爾。

我能想象的最佳解決方案。我們應該只有一個「循環」事件監聽器。在視頻開始在

let loopCount = 0; 
 
let throttle = true; 
 
document.querySelector('video').addEventListener("timeupdate",() => { 
 
    const video = document.querySelector('video'); 
 
    if (video.currentTime === 0 && throttle) { 
 
     throttle = false, 
 
     loopCount += 1; 
 
     console.log(loopCount); 
 
     setTimeout(()=> { 
 
      throttle = true; 
 
     }, 500); 
 
    } 
 
}, true);
<video autoplay muted loop src="https://rawgit.com/bower-media-samples/big-buck-bunny-480p-5s/master/video.mp4"></video>