JS – preventing several audio files from playing at the same time

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) => {
      musicTrack.paused ? musicTrack.play() : musicTrack.pause();


Read more here: https://stackoverflow.com/questions/66327328/js-preventing-several-audio-files-from-playing-at-the-same-time

Content Attribution

This content was originally published by Pedro Cobos at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: