Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to distinguish "seek" from "pause" via YouTube Player IFrame API

I have a youtube video that I've embedded with youtube's iFrame API. I would like to:

  • show a translucent overlay when a user pauses the video (WORKS)
  • hide that overlay when the user plays the video (WORKS)
  • NOT show an overlay when the user is "seeking" via the youtube controls (POSSIBLE?)

Having trouble controlling the seek behavior. Is it possible?

To reproduce, hold the seek at the same position for a few seconds and watch the overlay appear. Example jsfiddle is here: http://jsfiddle.net/dNU84/3/

var ytvideo;
window.onYouTubePlayerAPIReady = function () {
    ytvideo = new YT.Player('ytvideo', {
        width: '400',
        height: '300',
        videoId: 'BOksW_NabEk',
        playerVars: {
            'autoplay': 1,
            'controls': 1
        },
        events: {
            "onStateChange": onPlayerStateChange
        }
    });
}

function showOverlay() {
    if ($('.video .video-overlay').length) $('.video .video-overlay').fadeIn(1200);
}

function hideOverlay() {
    if ($('.video .video-overlay').length) $('.video .video-overlay').hide();
}

var overlay;
function onPlayerStateChange(event) {
    console.log(event.data);
    clearTimeout(overlay);

    // youtube fires 2xPAUSED, 1xPLAYING on seek
    if (event.data == YT.PlayerState.PAUSED) {
        overlay = setTimeout(showOverlay, 1000);
    }
    if (event.data == YT.PlayerState.PLAYING) {
        overlay = hideOverlay();
    }
}
like image 270
epylinkn Avatar asked Dec 21 '22 01:12

epylinkn


2 Answers

Unfortunately, the YouTube player APIs don't have a reliable way to report on a "seek" state. If you're interested, here's a link to an (older) explanation as to why this is the case:

https://groups.google.com/forum/#!topic/youtube-api-gdata/1xGLZ54YOPI

If you have any desire to use a chromeless player instead of the default one with YouTube controls, you can get around this limitation by listening for events on your custom scrubber ... as a simple example, jQuery UI's slider can be set up as a scrubber for a chromeless player and report the "seek" state by using the 'start,' 'stop,' and 'slide' events.

like image 131
jlmcdonald Avatar answered Dec 28 '22 07:12

jlmcdonald


I know this question is old, but I was just searching for a solution to this because I show an overlay on pause, but the overlay was showing each time the user would seek as well due to both event values being 2.

The easiest solution I've come across is to set a one second timeout:

setTimeout(function() {
  if ( event.target.getPlayerState() == 2 ) {
    // execute your code here for paused state
  }
}, 1000)

This will only execute code on the paused state, and not on seek because after the 1 second timeout the PlayerState would be 1 again if it were the user seeking.

like image 21
Sean Avatar answered Dec 28 '22 05:12

Sean