Javascript 如何自动播放静音的 Youtube 视频 (IFrame API)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8869372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:51:54  来源:igfitidea点击:

How do I automatically play a Youtube video (IFrame API) muted?

javascriptjqueryyoutube

提问by TIMEX

<iframe class="youtube-player" type="text/html" src="http://www.youtube.com/embed/JW5meKfy3fY?wmode=opaque&autohide=1&autoplay=1&volume=0&vol=0&mute=1" frameborder="0">&lt;br /&gt;</iframe>

The video isn't muted! I want volume to be 0 when it first plays...

视频没有静音!我希望第一次播放时音量为0...

回答by Gagandeep Singh

Youtube don't provide muting through url parameter (see http://code.google.com/apis/youtube/player_parameters.html).

Youtube 不通过 url 参数提供静音(请参阅http://code.google.com/apis/youtube/player_parameters.html)。

You have to use javascript for that. see http://code.google.com/apis/youtube/js_api_reference.htmlfor details.

为此,您必须使用 javascript。有关详细信息,请参阅http://code.google.com/apis/youtube/js_api_reference.html

However, please note the warning on the page linked above: "The deprecation of the YouTube JavaScript Player API was announced on January 27, 2015. YouTube Flash embeds have also been deprecated. See the deprecation policy for more information. Please migrate your applications to the IFrame API, which can intelligently use whichever embedded player – HTML () or Flash () – the client supports."

但是,请注意上面链接页面上的警告:“YouTube JavaScript Player API 已于 2015 年 1 月 27 日宣布弃用。YouTube Flash 嵌入也已弃用。有关更多信息,请参阅弃用政策。请将您的应用程序迁移到IFrame API,它可以智能地使用客户端支持的任何嵌入式播放器——HTML () 或 Flash ()。”

Html

html

<iframe class="youtube-player" id="player" type="text/html" src="http://www.youtube.com/embed/JW5meKfy3fY?wmode=opaque&autohide=1&autoplay=1&enablejsapi=1" frameborder="0">&lt;br /&gt;</iframe>

please note enablejsapi=1 in the url.

请注意 url 中的 enablejsapi=1 。

Javascript

Javascript

var player =  iframe.getElementById('player');
player.mute();

Update

更新

Previous code had some issues and did not work with current API (playerVars syntax was wrong). Here is the updated code. You may need to tinker with the parameters you need.

以前的代码有一些问题,不能与当前的 API 一起使用(playerVars 语法错误)。这是更新的代码。您可能需要修改所需的参数。

         
    <div id="player"></div>
    <script>
      // 1. 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);

      // 2. 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%',
          playerVars: {
                    autoplay: 1,
                    loop: 1,
                    controls: 0,
                    showinfo: 0,
                    autohide: 1,
                    modestbranding: 1,
                    vq: 'hd1080'},
          videoId: '1pzWROvY7gY',
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
      }

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

      var done = false;
      function onPlayerStateChange(event) {
        
      }
      function stopVideo() {
        player.stopVideo();
      }
    </script>

回答by Deepak Gupta

Try this its working fine

试试这个它工作正常

<html><body style='margin:0px;padding:0px;'>
        <script type='text/javascript' src='http://www.youtube.com/iframe_api'></script><script type='text/javascript'>
                var player;
        function onYouTubeIframeAPIReady()
        {player=new YT.Player('playerId',{events:{onReady:onPlayerReady}})}
        function onPlayerReady(event){player.mute();player.setVolume(0);player.playVideo();}
        </script>
        <iframe id='playerId' type='text/html' width='1280' height='720'
        src='https://www.youtube.com/embed/R52bof3tvZs?enablejsapi=1&rel=0&playsinline=1&autoplay=1&showinfo=0&autohide=1&controls=0&modestbranding=1' frameborder='0'>
        </body></html>

回答by JD - DC TECH

The player_apiwill be deprecated on Jun 25, 2015. For play youtube videos there is a new api IFRAME_API

player_api将在6月25日,2015年被弃用,对于播放YouTube视频有一个新的API IFRAME_API

It looks like the following code:

它看起来像下面的代码:

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

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

回答by ldiqual

You can select the video player and then set its volume:

您可以选择视频播放器,然后设置其音量:

var mp = iframe.getElementById('movie_player');
mp.setVolume(0);

Source: http://userscripts.org/scripts/review/49366

来源:http: //userscripts.org/scripts/review/49366

回答by Tarik

The accepted answer works pretty good. I wanted more control so I added a couple of functions more to the script:

接受的答案效果很好。我想要更多的控制,所以我在脚本中添加了几个函数:

function unmuteVideo() {
    player.unMute();
    return false;
  }
  function muteVideo() {
    player.mute();
    return false;
  }
  function setVolumeVideo(volume) {
    player.setVolume(volume);
    return false;
  }

And here is the HTML:

这是 HTML:

<br>
<button type="button" onclick="unmuteVideo();">Unmute Video</button>
<button type="button" onclick="muteVideo();">Mute Video</button>
<br>
<br>
<button type="button" onclick="setVolumeVideo(100);">Volume 100%</button>
<button type="button" onclick="setVolumeVideo(75);">Volume 75%</button>
<button type="button" onclick="setVolumeVideo(50);">Volume 50%</button>
<button type="button" onclick="setVolumeVideo(25);">Volume 25%</button>

Now you have more control of the sound... Check the reference URL for more:

现在您可以更好地控制声音……查看参考 URL 了解更多信息:

YouTube IFrame Player API

YouTube IFrame 播放器 API

回答by Front-end Developer

var video1;

function onYouTubeIframeAPIReady(){
 player = new YT.Player("video1", {
  videoId: "id-number",
  width: 300,
  height: 200, 
  playerVars: {
   "autoplay": 1, // and 0 means off
   "controls": 1,
   "showinfo": 0,
   "modestbranding": 0,
   "loop": 1,
   "fs": 0,
   "cc_load_policy": 0,
   "iv_load_policy": 3,
   },
  events: {
      'onReady': onPlayerReady
  }
 });
  }

function onPlayerReady(event) {
    event.target.mute();
    event.target.setVolume(0); //this can be set from 0 to 100
}

Remember that the sound will not be muted in IE and Safari.

请记住,在 IE 和 Safari 中不会静音。