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

我们两清 提交于 2019-12-11 02:07:39

问题


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:


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>


来源:https://stackoverflow.com/questions/30771457/how-can-i-determine-if-standard-audio-player-is-playing-a-song

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!