How to Mute All Sound in a Page with Js

How to mute all sound in a page with JS?

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.

Audio mute and unmute button in html

Try once with this code it will work fine.

JavaScript Code

function toggleMute() {
var myAudio = document.getElementById('audio_playo24');
myAudio.muted = !myAudio.muted;
}

HTML Code

<audio id="audio_playo24" controls>
<source src="voice/vo3.mp3" type="audio/mp3" />
</audio>
<a href="javascript:void(0);" onclick="toggleMute()">Mute/Unmute</a>

mute all audio when users tab away from the site

You can listen to the blur event on the window object to detect when the user switches tabs or apps:

window.addEventListener('blur', () => console.log('blur'))

Take care though, as this fires on all occasions when the window loses focus, including for example, pressing ctrl+f to open the find dialog or clicking on an extension popup.

As to audio, assuming you are using standard html5 <audio> element, you can set the muted property to true:

document.getElementById('my-audio-tag').muted = true


Related Topics



Leave a reply



Submit