跟踪观看的视频百分比不起作用(timeupdate和vimeo)。为什么?

问题描述 投票:1回答:1

[通过一些谷歌搜索,我想到了以下代码来跟踪播放,结束和视频进度(已观看视频的百分比)。我使用Vimeo API Tracking作为输入。

PLAYEND起作用。当观看10%的视频时,TIMEUPDATE也有效,但console.log无效。我无法弄清楚自己在做什么错。

<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>video-test-vimeo</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>

<iframe src="https://player.vimeo.com/video/76979871" width="640" height="360" frameborder="0" allowfullscreen allow="autoplay; encrypted-media"></iframe>

<script src="https://player.vimeo.com/api/player.js"></script>
<script>
    var iframe = document.querySelector('iframe');
    var player = new Vimeo.Player(iframe);

    player.on('play', function() {
        console.log('played the video!');
    });
	
	player.on('ended', function() {
        console.log('ended the video!');
    });
	
	player.on('timeupdate', function(data) {
		console.log('Percentage watched: '+data.percent);
    	if (data.percent == 0.1) {
			console.log('10% of video watched');
     	}
 });
</script>
</body>
</html>
javascript vimeo
1个回答
1
投票

@@ Marten Hoekstra不确定您是否已解决此问题,但为了后代,我将为您提供完整的答案:

如果运行代码,您将在控制台中看到:

Percentage watched: 0.097 
Percentage watched: 0.101 
Percentage watched: 0.105

但是,当百分比正好为0.1时,您的代码行if (data.percent == 0.1)尝试打印。这并不清楚。这是由于时间更新事件的性质所致,您可以在此处阅读:https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/timeupdate_event。这说:

事件频率取决于系统负载,但会在大约4Hz到66Hz之间抛出(假设事件处理程序的运行时间不超过250ms)。

这意味着,尽管事件非常频繁地发生,但是不足以确保该值将<> 10%。因此,您应该在if语句中添加某种公差,以免依赖于确切的值。可能是这样的:const TOLERANCE = 0.002 ... if (data.percent >= (0.1 - TOLERANCE) && data.percent <= (0.1 + TOLERANCE))

© www.soinside.com 2019 - 2024. All rights reserved.