How to determine if a standard audio player plays a song?

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 want to determine if the above standard play button was pressed to play the song. If so, I need to first stop all other songs that can be played, for example,

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 use <input ...>to do what I desire; but I would like to avoid this if possible.

Any ideas?

+2
source share
1 answer

You can use the event playfor this, then iterate over all the other sound elements and cause a pause on them.

, this , (, , CSS ..).

pause() , , . , .

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>
+1

All Articles