I wrote a function that iterates over an array, creates a querySelector
, an audio
element, and addsEventListener
to play the audio element when clicking on a button.
The problem I have is that I can't figure out how to play just one track at a time. The ideal behavior would be that when the user clicks on a button, all of the other tracks stop or pause.
I tried using a for loop as suggested on similar solutions I found here in SO but it didn't work. I guess I am not adding it where it should be in order to control the flow.
Any help will be greatly appreciated, thanks.
const tracks = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
//
const newAudioTracks = () => {
tracks.forEach(function(track) {
const button = document.querySelector(`#track-${track}`);
const musicTrack = new Audio(`/music/track${track}.mp3`);
musicTrack.id = track;
button.addEventListener('click', (event) => {
event.preventDefault();
musicTrack.paused ? musicTrack.play() : musicTrack.pause();
})
})
}
newAudioTracks();
The problem is that your event will be fired for just one element, then you need to iterate over the others pausing one by one.
Here is one example, I passed the attribute controls instead of creating an external button to play, but the logic is the same if you use a custom button.
const tracks = Array.from(document.querySelectorAll('audio'));
tracks.forEach(function(track) {
track.addEventListener('play', (event) => {
tracks.forEach(function(track) {
if(track !== event.target) track.pause();
})
})
})
<audio src="https://upload.wikimedia.org/wikipedia/commons/8/8f/Test_mp3_opus_16kbps.wav" controls></audio>
<audio src="https://upload.wikimedia.org/wikipedia/commons/8/8f/Test_mp3_opus_16kbps.wav" controls></audio>
<audio src="https://upload.wikimedia.org/wikipedia/commons/8/8f/Test_mp3_opus_16kbps.wav" controls></audio>
<audio src="https://upload.wikimedia.org/wikipedia/commons/8/8f/Test_mp3_opus_16kbps.wav" controls></audio>