How to listen to seek event in youtube embed api

2019-04-07 04:07发布

Hi I am using youtube iframe embed API. I want to track seek video event by user. Please help me how can I track this.

标签: youtube-api
1条回答
成全新的幸福
2楼-- · 2019-04-07 04:43

There is no simple way to track the event with the api alone.

What you could to is running a javascript function in interval and check if the time difference measured is different from the one expecting

Here is an example code :

<html>
    <body>
        <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("ready");
                player = new YT.Player('player', {
                    height: '390',
                    width: '640',
                    videoId: 'cRmNPE0HwE8',
                    events: {
                        'onReady': onPlayerReady,
                            'onStateChange': onPlayerStateChange
                    }
                });
                //console.log(player);
            }

            function onPlayerReady(event) {
                event.target.playVideo();

                /// Time tracking starting here

                var lastTime = -1;
                var interval = 1000;

                var checkPlayerTime = function () {
                    if (lastTime != -1) {
                        if(player.getPlayerState() == YT.PlayerState.PLAYING ) {
                            var t = player.getCurrentTime();

                            //console.log(Math.abs(t - lastTime -1));

                            ///expecting 1 second interval , with 500 ms margin
                            if (Math.abs(t - lastTime - 1) > 0.5) {
                                // there was a seek occuring
                                console.log("seek"); /// fire your event here !
                            }
                        }
                    }
                    lastTime = player.getCurrentTime();
                    setTimeout(checkPlayerTime, interval); /// repeat function call in 1 second
                }
                setTimeout(checkPlayerTime, interval); /// initial call delayed 
            }
            function onPlayerStateChange(event) {

            }
        </script>
    </body>
</html>
查看更多
登录 后发表回答