0

我需要在用户访问页面时开发自动播放,实际应用谷歌文档中提供的代码片段: 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,但该实验也失败了 - 视频无法播放 您能帮忙吗?

4

1 回答 1

1

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

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

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

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/

于 2022-01-15T12:08:54.070 回答