Javascript 自动播放适用于浏览器,但不适用于 iPad

Javascript autoplay works on browser but not on iPad

我从post这里复制了一段代码,稍微修改了一下。自动播放在我的电脑上运行良好(使用 javascript),但在 iPad 上却不行。我一直在尝试使用 autoplay: 1 inside onYouTubeIframeAPIRead 但它没有帮助。

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

  // 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: '100%',
      width: '100%',
      videoId: '<?php echo $video;?>',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  // 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, <?php echo $length*1000+2000;?>);
      done = true;
    }
  }
  function stopVideo() {
    player.stopVideo();
  }
</script>

iOS 阻止自动播放具有音轨且通过与用户交互不在同一直接上下文中的处理程序自动播放的视频。

相关博客post:https://webkit.org/blog/6784/new-video-policies-for-ios/

您需要将其绑定到处理程序并保持相同的整体上下文,以便允许自动播放。我相信 Chrome 也将很快实施这项政策。