YouTube Iframe API - 在移动设备上播放视频

时间:2017-05-26 08:50:18

标签: javascript iframe youtube youtube-iframe-api

在搜索并找到许多类似的问题后,我找不到正确的答案。所以我正在使用YouTube Iframe API,我知道自动播放等不适用于手机。我创建了一个显示在手机上的元素,因此当用户点击该按钮时,它应播放视频。但我只收到此消息:“如果播放不能很快启动,请尝试重新启动设备”

var playElement = document.createElement("div");
playElement.style.display = "none";

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
   playElement.style.display = "block";
}

var player;
function onYouTubeIframeAPIReady() {
   player = new YT.Player(child, {
      width: '100%',
      height: '100%',
      videoId: youtubeID,
      playerVars: {
         'iv_load_policy': 3,
         'enablejsapi': 1,
         'disablekb': 1,
         'autoplay': 1,
         'loop': 0,
         'controls': 0,
         'showinfo': 0,
         'rel': 0,
         'mode': 'transparent'
      },
      events: {
         'onReady': onPlayerReady,
         'onStateChange': onPlayerStateChange
      }
   });
}

playElement.onclick = function() {
   player.playVideo();;
};

任何确实有实际工作解决方案的人?

1 个答案:

答案 0 :(得分:0)

记住玩家指的是ID为“玩家”的div。您可以从youtube api doc上的示例代码开始。它会在视频加载后自动播放。您也可以添加您的playerVar选项。

移动视频自动播放说明。你可以让它自动播放,但必须静音。因此,您可以尝试在加载时添加player.mute()并设置点击处理程序,以便在您喜欢的时候再次取消静音。

<!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
          },
          playerVars
        });
      }

      // 4. The API will call this function when the video player is ready.
      function onPlayerReady(event) {
        event.target.playVideo();
      }

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