I have 10 audio players with simple html audio tags on a html5 page. No jquery, no special audio js plugins, etc...
Does anyone has a simple script in js to pause all other players when the current player is playing ?
I don't want to use js plugins because i want to keep a simple audio html code.
An audio file that will automatically start playing: <audio controls autoplay>
The pause() method halts (pauses) the currently playing audio. Tip: This method is often used together with the play() method. Tip: Use the controls property to display audio controls (like play, pause, seeking, volume, etc, attached on the audio).
play() to Play Audio Files in JavaScript. We can load an audio file in JavaScript simply by creating an audio object instance, i.e. using new Audio() . After an audio file is loaded, we can play it using the . play() function.
By adding more "<audio>" tags you can add more audio players in the browser using HTML5...
you can use event delegation. Simply listen to the play event in the capturing phase and then pause all video file, but not the target one:
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);
Instead of looping over all audio tags on a page and pausing them, you can store a reference to the currently playing element, and have only that one pause when playing another.
document.addEventListener("play", function(evt) { if(this.$AudioPlaying && this.$AudioPlaying !== evt.target) { this.$AudioPlaying.pause(); } this.$AudioPlaying = evt.target; }, true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With