Play one of a set of audio clips randomly?

34 Views Asked by At

So I'm trying to setup a web-page where when you open it, it will play a random piece of music, and when that one finishes, it will play another directly after so you get a constant stream of music, but not in the same order every time. If this goes outside the bounds of HTML and I'm looking at for instance JavaScipt than that's fine.

I know this is probably a rather easy solution, but I'm new to HTML and trying to understand it better.

Thanks in advance if I don't get back to you soon!

1

There are 1 best solutions below

1
Richard Hamilton On

This is best solved using JavaScript, which is used to add behavior to a website. HTML is primarily used to structure your site.

We can get a collection of all audio elements with the querySelectorAll function. Then we find a random element with the next line and call the play method.

var audio = document.querySelectorAll("audio");

function playRandom() {
    audio[Math.floor(Math.random() * audio.length)].play()
}();

For the second part of your question, you would want to listen for the ended event. Inside the event listener function, you would then call the playRandom() function.

audio.addEventListener("ended", function() {
    playRandom();
});