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

问题描述 投票:0回答:7

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

这应该使 HTML5

<audio>
<video>
标签以及 Flash 和朋友静音。

javascript html flash audio mute
7个回答
31
投票

这可以在普通 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 初始化音频等项目通常不可能以编程方式进行限制。


8
投票

规则#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(希望如此)。

但是您明白了,迭代媒体、检查/存储播放状态以及静音/取消静音。


6
投票

我是这样做的:

[].slice.call(document.querySelectorAll('audio')).forEach(function(audio) {
    audio.muted = true;
});

5
投票

你可以做

[...document.querySelectorAll('audio, video')].forEach(el => el.muted = true)

Array.from(document.querySelectorAll('audio, video')).forEach(el => el.muted = true)

1
投票

@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); });
}

这对我有用


0
投票

保留对数组内所有音频/视频元素的引用,然后创建一个函数,在设置

.muted=true
的同时对它们执行循环。


0
投票

我觉得这个很有用...

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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.