Javascript 如何使用JS静音页面中的所有声音?
如何使用JS使页面上的所有声音静音 这将使HTML5Javascript 如何使用JS静音页面中的所有声音?,javascript,html,flash,audio,mute,Javascript,Html,Flash,Audio,Mute,如何使用JS使页面上的所有声音静音 这将使HTML5和标签以及Flash和friends一起静音。规则1:在加载页面时永远不要启用音频自动播放 无论如何,我将使用jQuery为HTML5演示: // WARNING: Untested code ;) window.my_mute = false; $('#my_mute_button').bind('click', function(){ $('audio,video').each(function(){ if
和
标签以及Flash和friends一起静音。规则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(希望如此)
但是你可以通过迭代媒体、检查/存储播放状态和静音/取消静音来了解这个想法。保留对数组中所有音频/视频元素的引用,然后创建一个函数,在设置
.mute=true
时对这些元素执行循环 这可以在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) );
}
当然,这只适用于
或
元素,因为像Flash或JS初始化音频这样的项目通常是不可能限制的 我是这样做的:
[].slice.call(document.querySelectorAll('audio')).forEach(function(audio) {
audio.muted = true;
});
你能行
[...document.querySelectorAll('audio, video')].forEach(el => el.muted = true)
或
我们需要更多的信息。你能详细说明一下吗?这在插件/用户中合适吗?@mplungjan,我的页面上有一个音频图标,当点击时,它会打开/关闭声音。Flash中的声音播放与HTML/JavaScript中的声音播放完全不同。看看你用来播放声音的API,它们通常有停止声音和调整音量的方法。@shmiddy告诉youtube@Ramin我非常怀疑你在Youtube上工作。你能再解释一下你的解决方案吗?没有我们可以使用的音频api吗…比如将目的地重新路由到新节点,而不将其连接到扬声器?只有在生成过程音频时才看到这一点,而不是使用Array.prototype.slice.call。你可以使用Array.fromreplaced
Array.prototype.slice
和[].slice
为了使它更易于阅读,我也添加了一个答案,说明了我的意思,我想这是更多的编写方法
Array.from(document.querySelectorAll('audio, video')).forEach(el => el.muted = true)