有没有办法用JavaScript检测YouTube视频开始播放?

6

嵌入YouTube iframe视频是否有“onload”事件?

我想要在我选择的音乐视频开始播放后才启动我的脚本。

我已经将一个“onload”事件附加到了YouTube视频所在的iframe上,但这并不对应实际视频的加载(缓冲完成准备播放)。它只对应于视频播放器在页面中加载时发生的情况。

换句话说,是否有任何方法使用JavaScript检测YouTube视频何时开始播放?


不确定为什么你的投票被 downvoted 了...但我认为再多点细节会有帮助。你能告诉我们你尝试了什么吗?技术上讲,你可以为任何一个元素添加一个 load 事件的监听器,当元素和它的所有子元素都加载完毕时,该事件将触发。 - vastlysuperiorman
@vastlysuperiorman 我已经更新了问题,提供了更多的背景信息,并且增加了一个更加直接的问题。 - Ulad Kasach
1个回答

4

你可以在Youtube Iframe API参考资料中找到你需要的所有内容。

我会在这里粘贴相关代码,但请注意,我只修改了一行代码以触发onReady警报。其余的代码都来自上述参考页面。

<!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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接