当用户在 YouTube 视频中寻找新位置时,我需要回调。我查看了 YouTube Javascript 和 iframe API,似乎 api 中没有这样的事件。
我错过了什么吗?
谢谢
迈克尔
当用户在 YouTube 视频中寻找新位置时,我需要回调。我查看了 YouTube Javascript 和 iframe API,似乎 api 中没有这样的事件。
我错过了什么吗?
谢谢
迈克尔
好的,我找到了一种不放弃 YouTube 嵌入式控件的方法。这个想法是在超时回调中监视当前时间,并在时间差“异常”时触发事件(直接是回调函数)。不是最细粒度的技术,因为检查是每秒执行两次,但是当我们需要在高级别处理 seekTo 事件时,它可以完成工作。希望这对其他人有所帮助,直到 Google 决定投资更新 API。
这是 YouTube iframe API 官方文档中给出的示例的修改版本:
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
console.log("YouTube API ready");
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
console.log("YouTube video ready");
}
function onPlayerStateChange(event) {
switch(event.data) {
case YT.PlayerState.CUED:
console.log("YouTube video CUED");
break;
case YT.PlayerState.PLAYING:
console.log("YouTube video PLAYING");
isPlaying = true;
checkSeek();
break;
case YT.PlayerState.BUFFERING:
console.log("YouTube video BUFFERING");
isPlaying = false;
break;
case YT.PlayerState.PAUSED:
console.log("YouTube video PAUSED");
isPlaying = false;
break;
case YT.PlayerState.ENDED:
console.log("YouTube video ENDED");
isPlaying = false;
break;
}
}
// A hack to work around the missing seek event
var checkSeekPeriod = 500;
var checkSeekMargin = 500;
var prevCurrentTime = 0;
var isPlaying = false;
function checkSeek()
{
if (!isPlaying) {
prevCurrentTime = -1;
return;
}
var currentTime= player.getCurrentTime();
if(prevCurrentTime > 0)
{
var diff = (currentTime - prevCurrentTime) * 1000;
if(Math.abs(diff - checkSeekPeriod) > checkSeekMargin)
{
console.log("checkSeek diff = " + diff.toFixed(0) + "ms");
onPlayerSeekTo(currentTime);
}
}
prevCurrentTime = currentTime;
setTimeout(function() {
return checkSeek();
}, checkSeekPeriod);
};
function onPlayerSeekTo(t) {
console.log("YouTube player seek: " + t + "s");
}
</script>
</body>
</html>