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?
Got it answered on Reddit:
Thanks!