Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen to seek event in youtube embed api

Tags:

youtube-api

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.

like image 602
patilvikasj Avatar asked Mar 27 '15 05:03

patilvikasj


1 Answers

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>
like image 133
dvhh Avatar answered Sep 19 '22 23:09

dvhh