当youtube视频开始播放时,有没有办法用javascript检测?

时间:2016-02-04 04:09:56

标签: javascript youtube

是否有" onload"嵌入式youtube iframe的视频?

我想在我选择的音乐视频开始后才开始播放我的剧本。

我将onload事件粘贴到youtube视频传入的iframe上,但这与实际视频的加载(缓冲已准备好播放)无关。它仅对应于视频播放器已加载到页面中的时间。

换句话说,有什么方法可以在youtube视频开始播放时使用javascript进行检测吗?

1 个答案:

答案 0 :(得分:3)

您正在寻找的所有内容都可以在Youtube Iframe API reference中找到。

我也会在这里粘贴相关代码,但要注意我只修改了一行来触发警报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>