简体   繁体   中英

Javascript play mp3 from random number

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM