28

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

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

Zach Saucier
  • 24,871
  • 12
  • 85
  • 147
TheOne
  • 10,819
  • 20
  • 81
  • 119

6 Answers6

30

This can 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() {
    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 are impossible to restrict programmatically in general.

Zach Saucier
  • 24,871
  • 12
  • 85
  • 147
  • This also unfortunately doesn't work for those elements in iframes (which is very typical for advertisements..). In general this, (and even less the other answers), are not a good solution. – Christian Jun 23 '23 at 09:42
  • @Christian it's the best solution that there is :) if the iframes are on the same domain then you can use this approach for it, though it's a little more involved – Zach Saucier Jun 23 '23 at 14:38
8

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.

David Strencsev
  • 1,065
  • 11
  • 11
6

I did it like this:

[].slice.call(document.querySelectorAll('audio')).forEach(function(audio) {
    audio.muted = true;
});
John Doherty
  • 3,669
  • 36
  • 38
5

You can do

[...document.querySelectorAll('audio, video')].forEach(el => el.muted = true)

or

Array.from(document.querySelectorAll('audio, video')).forEach(el => el.muted = true)
aljgom
  • 7,879
  • 3
  • 33
  • 28
1

@zach-saucier

function muteMe(elem) {elem.muted = false;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); });
}

This worked for me

0

Hold a reference to all audio/video elements inside an array and then make a function which performs a loop over them while setting the .muted=true.

Gooshan
  • 2,361
  • 1
  • 20
  • 15