Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mute all sound in a page with JS?

Tags:

How can I mute all sound on my page with JS?

This should mute HTML5 <audio> and <video> tags along with Flash and friends.

like image 684
TheOne Avatar asked Dec 26 '12 18:12

TheOne


People also ask

How do I mute audio in HTML?

In this article, we mute the audio by using the muted attribute in the <audio> tag of the HTML document. It is used to define that the audio should be muted on the webpage.


2 Answers

This can easily be done in vanilla JS:

// Mute a singular HTML5 element function muteMe(elem) {     elem.muted = true;     elem.pause(); }  // Try to mute all video and audio elements on the page function mutePage() {     var elems = document.querySelectorAll("video, audio");      [].forEach.call(elems, function(elem) { muteMe(elem); }); } 

or in ES6:

// Mute a singular HTML5 element function muteMe(elem) {     elem.muted = true;     elem.pause(); }  // Try to mute all video and audio elements on the page function mutePage() {     document.querySelectorAll("video, audio").forEach( elem => muteMe(elem) ); } 

This, of course, only works with <video> or <audio> elements, as items like Flash or JS initialized audio is impossible to restrict in general.

like image 149
Zach Saucier Avatar answered Oct 24 '22 01:10

Zach Saucier


Rule #1: Never enable audio autoplay upon page loading.

Anyway I'll show for HTML5 using jQuery:

// WARNING: Untested code ;)  window.my_mute = false;  $('#my_mute_button').bind('click', function(){      $('audio,video').each(function(){          if (!my_mute ) {              if( !$(this).paused ) {                 $(this).data('muted',true); //Store elements muted by the button.                 $(this).pause(); // or .muted=true to keep playing muted             }          } else {              if( $(this).data('muted') ) {                 $(this).data('muted',false);                 $(this).play(); // or .muted=false             }          }     });      my_mute = !my_mute;  }); 

Flash Media Players depends on the custom API (hopefuly) exposed to JavaScript.

But you get the idea, iterate through media, check/store playing status, and mute/unmute.

like image 25
David Strencsev Avatar answered Oct 24 '22 02:10

David Strencsev