JavaScript 按钮停止页面上的所有音频

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31307146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:31:15  来源:igfitidea点击:

JavaScript Button Stop All Audio on Page

javascripthtmlbuttonaudioplayback

提问by Samiul Haque Sohan

I'm using a embed player from mixlr.com to play audio. Now I need a button to stop the whole site's audio. Though the player have it's own play pause button. But I need my own button to control the whole site's audio where if i click on pause button it'll pause my whole site's audio. Can anybody help me please?

我正在使用 mixlr.com 的嵌入播放器来播放音频。现在我需要一个按钮来停止整个站点的音频。虽然播放器有自己的播放暂停按钮。但是我需要我自己的按钮来控制整个网站的音频,如果我点击暂停按钮,它将暂停我整个网站的音频。有人可以帮我吗?

回答by Samuel Liew

Pause all audio with one button:

一键暂停所有音频:

document.getElementById('stopButton').onclick = function() {
  var sounds = document.getElementsByTagName('audio');
  for(i=0; i<sounds.length; i++) sounds[i].pause();
};
<audio src="http://www.noiseaddicts.com/samples_1w72b820/1456.mp3" autoplay loop>
  Your browser does not support the <code>audio</code> element.
</audio>

<audio src="http://www.noiseaddicts.com/samples_1w72b820/3717.mp3" autoplay loop>
  Your browser does not support the <code>audio</code> element.
</audio>

<audio src="http://www.noiseaddicts.com/samples_1w72b820/118.mp3" autoplay loop>
  Your browser does not support the <code>audio</code> element.
</audio>

<input id="stopButton" type="button" value="Stop All Audio" />

回答by Dom Kelly

<script type="text/javascript">
document.addEventListener('play', function(e){
    var audios = document.getElementsByTagName('audio');
    for(var i = 0, len = audios.length; i < len;i++){
        if(audios[i] != e.target){
            audios[i].pause();
        }
    }
}, true);

</script>

回答by Sorwar Hossain Limon

Below code may help someone achieving this.

下面的代码可能会帮助某人实现这一目标。

var audioMap = new Map();
var rappers = document.querySelectorAll('.rapper');
rappers.forEach(function(rapper){
    audioMap.set(rapper, new Audio());
    rapper.addEventListener('click', function(){
        var audio = new Audio($(this).data('audio'));
        audio.play();
        audioMap.set(this, audio);
        var current = audioMap.get(this);
        // console.log('get', current);
        audioMap.forEach(function(audio){
            if( audio != current ){
                audio.pause();
                audio.currentTime = 0;
            }
        });
    });
});