你如何将嵌入式Youtube播放器静音?

Jon*_*han 20 javascript youtube youtube-api

我正在尝试使用Youtube播放器,但默认情况下我无法将其静音.

function onPlayerReady() {
    player.playVideo();
    // Mute?!
    player.mute();
    player.setVolume(0);
}
Run Code Online (Sandbox Code Playgroud)

我如何从一开始就将其静音?

小提琴


更新:

不推荐使用JavaScript Player API.
请使用iframe嵌入.

Jon*_*han 25

事实证明player.mute()工作正常.它只需要参数enablejsapi=1.小提琴中的初始测试不起作用,因为玩家启动有错误.以下作品.

HTML:

<iframe id="ytplayer" type="text/html" src="https://www.youtube-nocookie.com/embed/zJ7hUvU-d2Q?rel=0&enablejsapi=1&autoplay=1&controls=0&showinfo=0&loop=1&iv_load_policy=3" frameborder="0" allowfullscreen></iframe>
Run Code Online (Sandbox Code Playgroud)

JS:

var player;

function onYouTubeIframeAPIReady() {
    player = new YT.Player('ytplayer', {
        events: {
            'onReady': onPlayerReady
        }
    });
}

function onPlayerReady(event) {
    player.mute();
    player.playVideo();
}
Run Code Online (Sandbox Code Playgroud)

小提琴

感谢Gagandeep Singh和Anton King的指点 enablejsapi=1

  • [这是工作小提琴](http://jsfiddle.net/BFDKS/966/)有一个真实的YouTube视频,而不是在这里使用的`youtube-nocookie` (6认同)
  • jsfiddle不会使视频静音. (3认同)

Art*_*lev 8

由于某些原因,以上所有答案对我都不起作用.我不得不在Youtube API上使用或折旧方法可能是奇怪的wordpress主题,我不确定.使播放器静音的唯一方法是将下面的代码插入到标签中.

// Loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/player_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // Replaces the 'ytplayer' element with an <iframe> and
  // YouTube player after the API code downloads.
  var player;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('ytplayer', {
        height: '390',
        width: '640',
        videoId: 'YOUR_VIDEO_ID',
        playerVars: {
          autoplay: 1,
          controls: 1,
          disablekb: 1,
          hl: 'ru-ru',
          loop: 1,
          modestbranding: 1,
          showinfo: 0,
          autohide: 1,
          color: 'white',
          iv_load_policy: 3,
          theme: 'light',
          rel: 0
        },
        events: {
            'onReady': onPlayerReady,
        }
    });
  }

function onPlayerReady(event){
    player.mute();
}
Run Code Online (Sandbox Code Playgroud)
<div id="ytplayer"></div>
Run Code Online (Sandbox Code Playgroud)