1

I want to have a mute button for my site, so when it's pressed it will unmute / mute the audio playing from the background video. The js I have rn is this. Is there any way I can implement a button with this code?

`enter code here

var videos = [
'D1sZ_vwqwcE',
'BC_Ya4cY8RQ',
'HPc8QMycGno',
'JDglMK9sgIQ',
'hgKDu5pp_fU',
'oKMNj8v2gKE',
'TfnRTifSWh0',
'xO3aB5C3dpQ',
'v5hepekcHkk',
'4kjpZ_sPxzc',
];

var index=Math.floor(Math.random() * videos.length);
var html='<div class="video-background"><div class="video-foreground"><iframe frameborder="0" src="https://www.youtube.com/embed/' +videos[index] + '?controls=1&amp;showinfo=0&amp;rel=0&amp;autoplay=1&amp;iv_load_policy=3&amp;&mute=1" allow="autoplay""></iframe></div></div>';
document.write(html);

site for reference: https://enph.la

Zenithvox
  • 83
  • 9
  • 1
    Use [YouTube Iframe Player API instead](https://developers.google.com/youtube/iframe_api_reference) - see [working example](http://jsfiddle.net/Bvance/8bzxp9c2/) - credits: [Custom mute/unmute button Youtube API](https://stackoverflow.com/q/45807269/12511801) – Marco Aurelio Fernandez Reyes Feb 11 '22 at 16:02

1 Answers1

0

I deserve no credit for this answer, but wanted to point out that the described issue actually got solved in Custom mute/unmute button Youtube API quite well using the YouTube API as it can be seen in this working example from Marco Aurelio Fernandez Reyes (somehow it just works on jsfiddle, but not on stackoverflow...):

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;

function onYouTubeIframeAPIReady() {
  player = new YT.Player('youtube-video', {
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
}

function onPlayerReady() {
  console.log("hey Im ready");
  //do whatever you want here. Like, player.playVideo();

}

function onPlayerStateChange() {
  console.log("my state changed");
}

document.getElementById("mute").addEventListener('click', function(event) {
  console.log(player);

  if (player.isMuted()) {
    player.unMute();
  } else {
    player.mute();
  }
});
#mute {
  width: 50px;
  height: 50px;
  background-color: red;
}
<iframe id="youtube-video" width="560" height="315" src="https://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&
    autoplay=1
    &disablekb=1
    &enablejsapi=1
    &loop=1
    &controls=0
    &mute=0" frameborder="0" enablejsapi="1" allowfullscreen></iframe>
<div id="mute">
</div>
<p>
Press red square to mute/unmute
</p>

Since a comment easily be overlooked, I just wanted to point out the working solution.

Simon Ferndriger
  • 4,455
  • 6
  • 28
  • 53