YouTube自动播放静音

时间:2016-10-23 10:23:20

标签: javascript html youtube autoplay

我想在我的网站上自动播放静音的视频。我找到了一些似乎有效的代码,但它并没有。为什么这个javascript和HTML代码不起作用?

<div id="player"></div>

<script>
  // 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');
  tag.src = "http://www.youtube.com/player_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 onYouTubePlayerAPIReady() {
    player = new YT.Player('player', {
      playerVars: { 'autoplay': 1, 'controls': 1,'autohide':1,'wmode':'opaque' },
      videoId: 'RDfjXj5EGqI',
      events: {
        'onReady': onPlayerReady}
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
    event.target.mute();
  } </script>

jsFiddle for testing:https://jsfiddle.net/qswpr8tL/

谢谢!

1 个答案:

答案 0 :(得分:0)

请构建你的onReady处理程序:

var player;
// ...
function onPlayerReady(event) {
  player.mute();
}

根据documentation,您必须在mute对象上调用player方法。