The random-source Web Component allows you to cycle randomly through different audio or video sources, utilising existing HTML elements and providing an elegant fallback experience.
Origin
In my ongoing efforts to wrap up small features I have on my website into neat little standalone Web Components I've set my eyes on the fun audio button on the homepage of my website (the little megaphone icon next to my name 📣). I get a lot of comments on it which causes me to follow up by saying that you can keep clicking it to get more sound clips!
Right now it's built using regular JavaScript and frankly a far too complex server function to randomly return a different audio URL to set on the hidden audio element. I think the only reason I used a server function is so that the HTML source didn't spoil the surprise, however that's a bit extreme and I think people would much rather spam the button than fiddle with the HTML in the inspector.
So how about instead of using complex fetch requests and server functions I use the very reliable source element, add multiple file sources to an audio (or video) element and let JavaScript randomly pick a new source after each play?
Enter random-source
The <random-source> component is designed to be wrapped around a regular audio or video element. After that you can drop in as many source elements as you like with different source URLs. After each play of the video or audio the source will be updated with a random source from the nested source elements.

Note that for reliability, consistency and performance reasons the first play will always be the first source element added. If you wish to be completely random on every load I'd recommend some sort of server side solution.
Usage
<random-source> can be used in a rather clean manner and can be wrapped around a regular audio or video element:
<script type="module" src="random-source.js"></script>
<random-source>
<audio controls>
<source src="https://darn.es/sounds/daviddarnes.m4a" />
<source src="https://darn.es/sounds/daviddarnes2.m4a" />
</audio>
</random-source>A very reduced example of using random-source
In the above example the audio element will change between daviddarnes.m4a and daviddarnes2.m4a randomly after each play.
Check out this live demo of an audio element cycling through 4 different audio files.
Further reading
If you'd like try the Web Component for yourself or learn more about templating you can check out the documentation and further examples on GitHub:

