Randomize audio file array with one button in HTML/Javascript to stop previous track and start new

23 views Asked by At

I have an array of 3-5 second audio files that I want to randomize on the click of a button.

const audioArray = ["sound1.mp3", "sound2.mp3", "sound3.mp3"];

 function playRandomAudio() {
  const audioIndex = Math.floor(Math.random() * audioArray.length);
  const audio = new Audio(audioArray[audioIndex]);
     audio.pause();
     audio.currentTime = 0;
     audio.play();  
}
<button onclick="playRandomAudio()" type="button">Play Audio</button>

The problem: I can't get the last track to stop playing when the new one starts. If you click the button using the code below, the second click makes a track play over the first click, and the third click overlays yet another audio track on top of the other two.

Suggestions?

1

There are 1 answers

0
Kirstie Keill On

Got it answered on Reddit:

const audioArray = ["sound1.mp3", "sound2.mp3", "sound3.mp3"];
let currentAudio;

function playRandomAudio() {
    // Stop the current audio if it exists
    if (currentAudio) {
        currentAudio.pause();
        currentAudio.currentTime = 0;
    }

    const audioIndex = Math.floor(Math.random() * audioArray.length);
    const audio = new Audio(audioArray[audioIndex]);

    // Set the currentAudio to the new audio
    currentAudio = audio;

    // Play the new audio
    audio.play();
}

Thanks!