Is a Youtube buffer finish event possible

Viewed 1633
2 Answers

I know this question is old but the answer may still be helpful to some:

The YouTube video can be in one of 6 states:

  • -1 – unstarted
  • 0 – ended
  • 1 – playing
  • 2 – paused
  • 3 – buffering
  • 5 – video cued

When this state changes (i.e. when the video stops buffering and enters a 'paused' or a 'played' state), the "onStateChange" event is triggered. So, keep track of the previous state and the new state. When the previous state is 'buffering' and the new state is 'ended', 'playing', or 'paused', then this means that the video finished buffering.

Here is an example:

<html>
<body>
  <div id="player"></div>
  <script>
    var player;
    var lastState;

    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() {
        player = new YT.Player('player', {
            height: '390',
            width: '640',
            videoId: 'M7lc1UVf-VE',
            events: {
                'onStateChange': onPlayerStateChange
            }
        });
    }


    function onPlayerStateChange(event) {
        if (lastState == YT.PlayerState.BUFFERING &&
            (event.data == YT.PlayerState.PLAYING || event.data == YT.PlayerState.PAUSED)) {
            alert('Buffering has completed!');
        }
        lastState = event.data;
    }
  </script>
</body>
</html>
Related