No onSeekTo event in the YouTube player api?

I need a callback when a user searches for a new position in a YouTube video. I looked at the Javascript and iframe YouTube APIs and it looks like there is no such event in the api.

Did I miss something?

thanks

Michael

+4
source share
1 answer

Ok, I found a way without giving up YouTubeโ€™s built-in controls. The idea is to track the current time in a timeout callback and trigger an event (directly the callback function) whenever the time difference is โ€œabnormalโ€. Not the finest-grained method, because the check is performed twice a second, but it does the job when we need to handle seekTo events at a high level. Hope this helps others until Google decides to invest in an API update.

The following is a modified version of the example in the official YouTube iframe API documentation:

<!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> 
+3
source

Source: https://habr.com/ru/post/1502241/


All Articles