The*_*One 20 javascript flash audio html5 mute
如何用JS将我的页面上的所有声音静音?
这应该将HTML5 <audio>和<video>标签与Flash和朋友一起静音.
Zac*_*ier 18
这可以在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); });
}
Run Code Online (Sandbox Code Playgroud)
或者在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) );
}
Run Code Online (Sandbox Code Playgroud)
当然,这仅适用于<video>或<audio>元素,因为像Flash或JS初始化音频这样的项目通常不可能限制.
规则#1:永远不要在页面加载时启用音频自动播放.
无论如何,我将使用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;
});
Run Code Online (Sandbox Code Playgroud)
Flash Media Players依赖于暴露给JavaScript的自定义API(hopefuly).
但是你得到了这个想法,遍历媒体,检查/存储播放状态,以及静音/取消静音.
我是这样做的:
[].slice.call(document.querySelectorAll('audio')).forEach(function(audio) {
audio.muted = true;
});
Run Code Online (Sandbox Code Playgroud)
你可以做
[...document.querySelectorAll('audio, video')].forEach(el => el.muted = true)
Run Code Online (Sandbox Code Playgroud)
或者
Array.from(document.querySelectorAll('audio, video')).forEach(el => el.muted = true)
Run Code Online (Sandbox Code Playgroud)