Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to detect with javascript when a youtube video starts playing?

Is there an "onload" of the video for an embeded youtube iframe?

I'd like to start my script only after the music video i have selected starts.

I have stuck an onload event onto the iframe the youtube video is delivered in, but that does not correspond to the loading (buffering has finished ready to play) of the actual video. It only corresponds to when the video player has been loaded in the page.

In other words, is there any way to detect with javascript when a youtube video starts playing?

like image 402
Ulad Kasach Avatar asked Sep 26 '22 11:09

Ulad Kasach


1 Answers

Everything you're looking for can be found in the Youtube Iframe API reference.

I'll paste the relevant code here as well, but be aware that I only modified one line to trigger an alert onReady. The rest of the code comes from the aforementioned reference page.

<!DOCTYPE html>
<html>
  <body>
    <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
    <div id="player"></div>

    <script>
      // 2. This code loads the IFrame Player API code asynchronously.
      var tag = document.createElement('script');

      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

      // 3. This function creates an <iframe> (and YouTube player)
      //    after the API code downloads.
      var player;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          height: '390',
          width: '640',
          videoId: 'M7lc1UVf-VE',
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
      }

      // 4. The API will call this function when the video player is ready.
      function onPlayerReady(event) {
        alert("Video Ready!");
        event.target.playVideo(); // You can omit this to prevent the video starting as soon as it loads.
      }

      // 5. The API calls this function when the player's state changes.
      //    The function indicates that when playing a video (state=1),
      //    the player should play for six seconds and then stop.
      var done = false;
      function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING && !done) {
          setTimeout(stopVideo, 6000);
          done = true;
        }
      }
      function stopVideo() {
        player.stopVideo();
      }
    </script>
  </body>
</html>
like image 115
vastlysuperiorman Avatar answered Nov 26 '22 07:11

vastlysuperiorman