从页面加载的url列表中选择一个随机的.mp3文件来自动播放?



现在我有这个

<audio autoplay>
<!-- <source src="https://a.pomf.cat/vmrlef.mp3" type="audio/mpeg">--> <!--  escape through the snow -->
<!-- <source src="https://files.catbox.moe/vif2j1.mp3" type="audio/mpeg"> <!-- sea map -->
<source src="https://files.catbox.moe/4abc2w.mp3" type="audio/mpeg"> <!-- ミク - prblm- -->
</audio>

,我不知道如何使它选择每一个随机在页面加载上,有没有一种方法喜欢有一个列表,然后使源src从列表中随机选择每次重新加载?非常新的HTML和任何帮助将非常感激!!^ ^

像这样

https://jsfiddle.net/mplungjan/6opnhymz/

const audioUrls = ["https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3",
"https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3",
"https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3"];
const rnd = Math.floor(Math.random()*audioUrls.length); // random number from 0 to length of array
const audio = new Audio(); // an audio object
const loadedAudio = () => audio.play(); // what happens after the audio successfully has been found
document.body.appendChild(audio); // add it to the page
audio.addEventListener('canplaythrough', loadedAudio, false); // add the event that will play, here "can it play?"
console.log(`Playing #${rnd}:${audioUrls[rnd]}`); // for us to see it works
audio.src = audioUrls[rnd]; // actual trigger to play the audio
audio.load(); // iOS may need this

最新更新