JavaScript Button Stop All Audio on Page
Asked Answered
A

3

5

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?

Andriette answered 9/7, 2015 at 2:35 Comment(1)
The mozilla site might be of some help: developer.mozilla.org/en-US/docs/Web/Guide/HTML/…Coastland
B
15

Pause all audio with one button:

document.getElementById('stopButton').addEventListener('click', () => {
  document.querySelectorAll('audio').forEach(el => el.pause());
});
<audio src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3" controls loop></audio>
<audio src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3" controls loop></audio>
<audio src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3" controls loop></audio>

<div>
  <input id="stopButton" type="button" value="Stop All Audio" />
</div>
Boatel answered 9/7, 2015 at 2:51 Comment(0)
F
7
<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>
Factitive answered 14/7, 2016 at 19:50 Comment(1)
When I am using the audio tag for my music library site, this comes in very handy to stop all sounds when another track is played.Factitive
Y
0

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;
            }
        });
    });
});
Yelp answered 16/10, 2017 at 6:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.