【问题标题】:(YouTube API): YT.Player doesnt work playVideo(YouTube API):YT.Player 无法播放视频
【发布时间】:2022-01-15 11:55:16
【问题描述】:

当用户访问页面时,我需要开发自动播放,实际应用 google doc 中提供的代码 sn-p: 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,但这个实验也失败了 - 视频没有播放 请问您能帮忙吗?

【问题讨论】:

    标签: youtube yt


    【解决方案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/

    【讨论】:

    • 感谢您的参考。
    • 我认为您所描述的是由于浏览器阻止自动播放的那些异常。在以下情况下允许自动播放有声:如果用户的媒体参与指数阈值已超过,则用户已与域交互(点击、点击等)或在桌面上进行交互,这意味着用户之前播放过有声视频。
    • 是的,你是对的。对于 Safary,它可以按预期工作,当然,它是浏览器策略。您是否知道一些可能对这种情况有所帮助的方法?
    • 不,我不抱歉。我想绕过它会很困难,因为它被硬编码到浏览器中,绕过它基本上意味着覆盖用户自己的配置。您可以在没有声音的情况下运行视频,并做一些事情让用户与网站进行交互,然后在运行的视频上启用声音。之后,如果用户切换页面,即使有声音也可以让它自动播放,因为之前已经完成了交互。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 2023-03-07
    • 2014-07-13
    • 2015-12-23
    • 2021-05-29
    • 2011-09-06
    • 1970-01-01
    相关资源
    最近更新 更多