[英]Get frame change in video HTML5
我需要檢測HTML 5中視頻的所有幀更改,我嘗試了以下代碼,但我無法獲得所有更改,只有我每秒可以獲得8或9次更新..
<body>
<canvas id="Canvas" width="800" height="450" style="position:absolute; left:5; top:5">Can't Load Canvas</canvas>
<video id="videoPlay" muted controls>
<source src="assets/soccer.webm" type="video/webm">
<source src="assets/soccer.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
</body>
<script type="text/javascript">
videoPlay.addEventListener('timeupdate', function (){
putOverlay();
});
function putOverlay(){
console.log(videoPlay.currentTime);
console.log("another frame");
}
</script>
</html>
我也嘗試了以下代碼,但是隨着時間的推移,使用定時器會導致幀與定時器給出的值之間失去同步。
<body>
<canvas id="LeCanvas" width="800" height="450" style="position:absolute; left:5; top:5">Can't Load Canvas</canvas>
<!-- Video -->
<video id="videoPlay" controls>
<source src="assets/soccer.webm" type="video/webm">
<source src="assets/soccer.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
</body>
<!-- Play Video-->
<script>
//Play Damn Video
var videoPlay = $('#videoPlay')[0];
videoPlay.play(1);
</script>
<!-- Canvas Animation -->
<script>
//Animation
function animate() {
console.log("frame change");
}
setInterval(animate, 1000/29.97);
</script>
對我的問題有什么建議嗎?
對不起我的英文
亞歷克斯
如上面的評論所述, timeupdate
每15-2550 timeupdate
才會觸發,實際上它似乎接近250毫秒。 它好像timeupdate
旨在提供足夠的精度,以顯示currentTime
每一秒。 所以你最好的選擇是運行一個以你想要的速度運行的計時器,並在每次迭代時查詢currentTime
。
但是,您應該使用requestAnimationFrame ,而不是使用setInterval
甚至setTimeout
。 這將大約每16毫秒(60fps)運行,但它將與視頻卡刷新率同步。 如果使用setTimeout
,您可能會在某些設備上看到閃爍或屏幕撕裂,尤其是移動設備。 它還允許瀏覽器在選項卡不可見時節省幀速率,以節省CPU周期(因此節省電池使用量)。
它也比setInterval
好,因為如果由於某種原因你的渲染代碼花費的時間超過了你所分配的30或16ms, setInterval
可能會堆積調用並導致計時問題,但requestAnimationFrame
將跳過幀以使你回到正軌。
假設您已經使用了上面的polyfill,代碼看起來像這樣:
var video = document.getElementById('videoPlay'),
lastTime = -1;
function draw() {
var time = video.currentTime;
if (time !== lastTime) {
console.log('time: ' + time);
//todo: do your rendering here
lastTime = time;
}
//wait approximately 16ms and run again
requestAnimationFrame(draw);
}
draw();
上面的代碼檢查時間,以確保您不會連續兩次繪制相同的幀。 你真的不需要它,但它會節省你幾個CPU周期。 但是當將視頻繪制到畫布時,該幀比currentTime報告的幀落后幾毫秒。 因此,如果您暫停視頻然后跳過,您幾乎肯定會落后一幀。 通常情況下,如果currentTime在我上一次抽獎后沒有改變,但是視頻暫停了,我會繼續畫每個周期半秒鍾左右。 或者你可以花點時間退房。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.