Javascript 如何使用 JS 将页面中的所有声音静音?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14044761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to mute all sound in a page with JS?
提问by TheOne
How can I mute all sound on my page with JS?
如何使用 JS 将页面上的所有声音静音?
This should mute HTML5 <audio>and <video>tags along with Flash and friends.
这应该使 HTML5<audio>和<video>标签与 Flash 和朋友一起静音。
采纳答案by David Strencsev
Rule #1: Never enable audio autoplay upon page loading.
规则 #1:永远不要在页面加载时启用音频自动播放。
Anyway I'll show for HTML5 using jQuery:
无论如何,我将使用 jQuery 展示 HTML5:
// 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.
Flash Media Players 依赖于向 JavaScript 公开的自定义 API(希望如此)。
But you get the idea, iterate through media, check/store playing status, and mute/unmute.
但是你明白了,遍历媒体,检查/存储播放状态,静音/取消静音。
回答by Zach Saucier
This can easily be done in vanilla JS:
这可以在 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:
或在 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.
当然,这仅适用于<video>或<audio>元素,因为 Flash 或 JS 初始化音频之类的项目通常是不可能限制的。
回答by John Doherty
I did it like this:
我是这样做的:
Array.prototype.slice.call(document.querySelectorAll('audio')).forEach(function(audio) {
audio.muted = true;
});
回答by Gooshan
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.
保存对数组内所有音频/视频元素的引用,然后创建一个函数,在设置.muted=true.

