Paul McFedries' Web Home


JavaScript Random Sounds

This Web page includes a JavaScript that plays a randomly selected sound file each time you load the page. Here are the instructions:

  • Add onLoad=PlaySound() to your <BODY> tag, like so:
       <BODY onLoad=PlaySound()>
    
  • Copy everything between the <SCRIPT> and </SCRIPT> tags and insert it somewhere inside your Web page.

  • You have to define the number of sounds available for playing by altering the value in the following line:
        var NumberOfSounds = 6
    
  • For this script to operate properly in Netscape 2.0, you have to specify the full URL of the sound file. To make this more flexible, use the soundDir variable to hold the URL of the directory in which your sound files are located. To do this, you'll need to edit the following line:
        var soundDir = "http://www.mcfedries.com/toys/"
    
  • You define your sound files by editing the following lines:
        sounds[1] = soundDir + "applause.au"
        sounds[2] = soundDir + "breaking_glass.au"
        sounds[3] = soundDir + "chirp.au"
        sounds[4] = soundDir + "doorbell.au"
        sounds[5] = soundDir + "gong.au"
        sounds[6] = soundDir + "cowbell.au"
    
Here's the full script:
<SCRIPT LANGUAGE="JavaScript">
<!--
// This function plays a random sound
function PlaySound() {

    // Use the following variable to 
    // specify the number of sound files
    var NumberOfSounds = 6

    // This variable holds the array of 
    // sound files to choose from
    var sounds = new BuildArray(NumberOfSounds)

    // This variable specifies the URL of the 
    // directory that contains the sound files
    var soundDir = "http://www.mcfedries.com/toys/"

    // Use the following variables to 
    // specify the sound files:
    sounds[1] = soundDir + "applause.au"
    sounds[2] = soundDir + "breaking_glass.au"
    sounds[3] = soundDir + "chirp.au"
    sounds[4] = soundDir + "doorbell.au"
    sounds[5] = soundDir + "gong.au"
    sounds[6] = soundDir + "cowbell.au"

    // Use the time (i.e., seconds) to get a random number
    var d = new Date()
    var secs = d.getSeconds()
    var rnd = (secs % sounds.length) + 1
    snd = sounds[rnd]

    // Use "href" method to play the sound 
    // (as though the user clicked it)
    window.location.href=snd

}

// This function is used to create a new array
function BuildArray(size){
    this.length = size
    for (var i = 1; i <= size; i++){
        this[i] = null}
    return this
}

//-->
</SCRIPT>


Copyright © 1995 - 2014 Paul McFedries and Logophilia Limited