如何用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 初始化音频等项目通常不可能以编程方式进行限制。
规则#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 媒体播放器依赖于暴露给 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); });
}
这对我有用
保留对数组内所有音频/视频元素的引用,然后创建一个函数,在设置
.muted=true
的同时对它们执行循环。
我觉得这个很有用...
var audio = new Audio("your.mp3");
audio.play();
function onClick() {
if( audio.muted === false ){
audio.muted= true;
audio.pause();
}
else{
audio.muted= false;
audio.play();
}
}