Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple audio html : auto stop other when current is playing with javascript

Tags:

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.

like image 743
hedi Avatar asked Nov 05 '13 13:11

hedi


People also ask

What is audio autoplay loop HTML?

An audio file that will automatically start playing: <audio controls autoplay>

How do you pause audio in HTML?

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).

How play audio with JavaScript and HTML?

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.

Can multiple audio sources can be played in HTML?

By adding more "<audio>" tags you can add more audio players in the browser using HTML5...


2 Answers

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); 
like image 111
alexander farkas Avatar answered Sep 28 '22 02:09

alexander farkas


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); 
like image 37
bryc Avatar answered Sep 28 '22 03:09

bryc