如何使用 JS 将页面中的所有声音静音?

IT技术 javascript html flash audio mute
2021-03-10 01:50:02

如何使用 JS 将页面上的所有声音静音?

这应该使 HTML5<audio><video>标签与 Flash 和朋友一起静音

6个回答

这可以在 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(希望如此)。

但是你明白了,遍历媒体,检查/存储播放状态,静音/取消静音。

没有我们可以使用的音频 api 吗......比如将目的地重新路由到新节点并且不将其连接到扬声器?
2021-04-19 01:50:02
仅在使用WebAudio API生成程序音频时才看到这一点
2021-05-07 01:50:02

我是这样做的:

[].slice.call(document.querySelectorAll('audio')).forEach(function(audio) {
    audio.muted = true;
});
更换Array.prototype.slice[].slice,以使其更具可读性
2021-04-15 01:50:02
你可以使用 Array.from 而不是 Array.prototype.slice.call
2021-05-03 01:50:02
我也用我的意思添加了一个答案,我想这是写它的更多方法stackoverflow.com/a/66562772/3577695
2021-05-04 01:50:02

你可以做

[...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); });
}

这对我有用