简体   繁体   English

Javascript从随机数播放mp3

[英]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... 在页面加载时-在为随机数(而非列表)运行脚本并向其中添加“ .mp3”后播放选定的mp3 ...

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. 您需要更改audio元素的src属性,而不是每次都添加另一个元素。

 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(); 注意,您可以调用myFunction(); anytime to change randomly the current mp3. 随时随机更改当前mp3。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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