Sometimes, we want to auto stop other audio players the when current one is playing with JavaScript.
In this article, we’ll look at how to auto stop other audio players the when current one is playing with JavaScript.
How to auto stop other audio players the when current one is playing with JavaScript?
To auto stop other audio players the when current one is playing with JavaScript, we can call the pause
method on the other audio players when the current one is playing.
For instance, we write:
<audio src='https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3' controls></audio>
<audio src='https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3' controls></audio>
<audio src='https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3' controls></audio>
to add 3 audio elements.
Then we write:
const audios = document.getElementsByTagName('audio');
for (const a of audios) {
a.onplay = (e) => {
for (const aa of audios) {
if (aa !== e.target) {
aa.pause()
}
}
}
}
to select all audio elements with getElementsByTagName
.
Then we loop through all the audio elements in audios
and set the a.onplay
property to a function that loops through each audio element in audios
.
If the audio element aa
isn’t the same as e.target
, which is the current audio element that’s playing, then we call pause
on it.
Therefore, we see that the audio players other than the current one will stop playing when the current one is playing.
Conclusion
To auto stop other audio players the when current one is playing with JavaScript, we can call the pause
method on the other audio players when the current one is playing.