Ben.Cohen Ben.Cohen - 4 days ago 4
Java Question

Javascript play mp3 from random number

I deleted my previous question as it wasn't clear enough.

Here's what I'm after:
On page load - play an mp3 chosen after running a script for a random number (not list) and adding the ".mp3" to it...

This is what I got so far and it's not working:



<script type="text/javascript">

function myFunction() {
var x = Math.floor((Math.random() * 6) + 1);
}

document.write ('<audio src= "media/' + x + '.mp3" controls autoplay></audio>')

</script>





Please help. thanks.

Answer

You need to change the src attribute of the audio element, not to add another element each time.

function myFunction() {
    var x = Math.floor((Math.random() * 6) + 1);
    document.getElementById("myAudio").src = "media/" + x + ".mp3";
}
<body onload="myFunction();">
    <audio id="myAudio" src="" controls autoplay></audio>
</body>

Note that you can call myFunction(); anytime to change randomly the current mp3.

Comments