(YouTube API):YT.Player 无法播放视频

(YouTube API): YT.Player doesnt work playVideo

我需要在用户访问页面时开发自动播放,实际应用 google 文档中提供的代码片段: https://developers.google.com/youtube/iframe_api_reference

<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: '360',
          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) {
        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>

它无法正常工作,视频无法播放/ 我尝试将 event.target.playVideo(); 放入 setTimeout 中,延迟时间为 1000、2000、3000,但是这个实验也失败了——视频没有播放 你能帮忙吗?

我假设您的问题是大多数浏览器实施的自动播放政策。 在大多数情况下它会阻止自动播放。

一个例外是当视频静音时自动播放会起作用。也许这对您的用例有用。

如需进一步参考,请访问:

https://developer.chrome.com/blog/autoplay/

https://support.mozilla.org/en-US/kb/block-autoplay

https://webkit.org/blog/7734/auto-play-policy-changes-for-macos/