如何使用JS静音页面上的所有声音?
这应该会将HTML5中的<audio>
和<video>
标签以及Flash和其他相关内容全部静音。
如何使用JS静音页面上的所有声音?
这应该会将HTML5中的<audio>
和<video>
标签以及Flash和其他相关内容全部静音。
这可以用原生 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));
}
<video>
或<audio>
元素,因为像Flash或JS初始化的音频等项目通常无法以编程方式限制。第一条规则:切勿在页面加载时启用音频自动播放。
无论如何,我将展示使用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媒体播放器依赖于自定义API(希望)暴露给JavaScript。
但是你可以通过遍历媒体,检查/存储播放状态以及静音/取消静音来实现这一点。
[].slice.call(document.querySelectorAll('audio')).forEach(function(audio) {
audio.muted = true;
});
[].slice
替换Array.prototype.slice
,使其更易读。 - John Doherty您可以这样做
[...document.querySelectorAll('audio, video')].forEach(el => el.muted = true)
或者
Array.from(document.querySelectorAll('audio, video')).forEach(el => el.muted = true)
@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); });
}
将所有音频/视频元素的引用保存在数组中,然后创建一个函数,在循环遍历它们时设置.muted=true
。