如何使用 JS 将页面上的所有声音静音?
这应该使 HTML5<audio>
和<video>
标签与 Flash 和朋友一起静音。
如何使用 JS 将页面上的所有声音静音?
这应该使 HTML5<audio>
和<video>
标签与 Flash 和朋友一起静音。
这可以在 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); });
}
或在 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) );
}
当然,这仅适用于<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;
});
Flash Media Players 依赖于向 JavaScript 公开的自定义 API(希望如此)。
但是你明白了,遍历媒体,检查/存储播放状态,静音/取消静音。
我是这样做的:
[].slice.call(document.querySelectorAll('audio')).forEach(function(audio) {
audio.muted = true;
});
你可以做
[...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); });
}
这对我有用