Webmaster Resources Center

Welcome to the Bravenet Resource Center. Use these resources to help make your web pages more advanced and fun to use.

Articles & Tutorials

Adding a Random Song to your Website

by Andrea Butterworth


Summary : So you've already mastered the skill of adding a song to your website, but you want to take it one step further. It's time to randomly play a song every time your webpage is loaded.

Here's a nice easy script that will randomly pick a song and play it when someone visits your Website.To start with, you'll have to collect a few songs that you like from the Bravenet Audio Archive. The only areas of the script that you will have to change are the number of songs in your list, and the URL or location of the song.

<script type="text/javascript">
var numberOfSongs = 3
var sound = new Array(numberOfSongs+1)
sound[0]= "http://www.yourwebsite.com/audiofolder/song1.mid"
sound[1]= "http://www.yourwebsite.com/audiofolder/song2.mid"
sound[2]= "http://www.yourwebsite.com/audiofolder/song3.mid"
function randomNumber(){
var randomLooper = -1
while (randomLooper < 0 || randomLooper > numberOfSongs || isNaN(randomLooper)){    randomLooper = parseInt(Math.random()*(numberOfSongs+1))
}
    return randomLooper
}
var randomsub = randomNumber()
var soundFile = sound[randomsub]
document.write ('<EMBED src= "' + soundFile + '" hidden=true autostart=true loop=true>')
</script>

That's all there is to it! Load up a folder full of songs and add them to your mini jukebox!

When Christmas comes, don't forget to swap out your play list with some Christmas Carols!