JavaScript Button Stop All Audio on Page

2020-07-18 05:44发布

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?

3条回答
乱世女痞
2楼-- · 2020-07-18 05:54

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" />

查看更多
神经病院院长
3楼-- · 2020-07-18 06:07
<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>
查看更多
姐就是有狂的资本
4楼-- · 2020-07-18 06:12

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;
            }
        });
    });
});
查看更多
登录 后发表回答