YouTube 播放器 API 中没有 onSeekTo 事件



当用户在YouTube视频中寻找新位置时,我需要回调。我查看了YouTube Javascript和iframe API,似乎API中没有这样的事件。

我错过了什么吗?

谢谢

迈克尔

好的,我找到了一种方法,而不会放弃YouTube嵌入式控件。这个想法是在超时回调中监视当前时间,并在时差"异常"时触发事件(直接是回调函数)。不是最细粒度的技术,因为检查每秒执行两次,但是当我们需要在高级别处理 seekTo 事件时,它可以完成工作。希望这将帮助其他人,直到谷歌决定投资更新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>

相关内容

  • 没有找到相关文章

最新更新