How can I determine if standard audio player is playing a song

85 views Asked by At

I have the following as part of my html (once for each of several songs):

<audio
     name="aMedia"
     id="aMedia"
     controls
     preload="auto">
<source src="audio/mysong.m4a">
</audio>

I wish to determine if the above standard Play button was pressed to play a song. If it was, I need to first stop all other songs that may be playing, e.g.,

function stopAllSongs()
{
    var allMedia = document.getElementsByName(theMedia), thisMedia;
    for (m=0; m < allMedia.length; m++)
    {
        thisMedia = allMedia[m];
        if (thisMedia.isPlaying())
            thisMedia.pause();
    }
}

I have seen successful uses of <input ...> to do what I wish; but I would like to avoid that if possible.

Any ideas?

1

There are 1 answers

1
AudioBubble On

You could use the play event for this, then iterate through all other audio elements and invoke pause on them.

You can use a common handler for all the audio elements, the this object will represent the actual audio element triggering the event (which in turn of course can be used to set a CSS class etc.).

pause() can be called even if the audio is already paused so we don't need to do additional checks for it. We just loop through the array of elements and skip the element that triggered the event.

Example

var audioElements = document.querySelectorAll("audio"), i;

// bind common handler for each audio element in page:
for(i = 0; i < audioElements.length; i++) 
  audioElements[i].addEventListener("play", playHandler);

// common handler
function playHandler() {
    // this = element triggering the event
    // pause all but ours (reusing previous audioElements NodeList collection here)
    for(var i = 0; i < audioElements.length; i++)
      if (this !== audioElements[i]) audioElements[i].pause();
}
<i>Preload time may vary, be patient... (due to links IE will not be able to play these)</i><br>Starting one will stop all others<br>
<audio preload="auto" controls src="https://github.com/epistemex/free-music-for-test-and-demo/blob/master/music/kf_feelme.mp3?raw=true"></audio><br>
<audio preload="auto" controls src="https://github.com/epistemex/free-music-for-test-and-demo/blob/master/music/kf_colibris.mp3?raw=true"></audio><br>
<audio preload="auto" controls src="https://github.com/epistemex/free-music-for-test-and-demo/blob/master/music/kf_limitless.mp3?raw=true"></audio><br>
<audio preload="auto" controls src="https://github.com/epistemex/free-music-for-test-and-demo/blob/master/music/kf_thebattle.mp3?raw=true"></audio>