Using JavaScript to play a sound file.

Place the following code within your page after the opening body tag:

<!-- Functions Code Block Start-->
<script>
/* Here we are creating two functions. The first to start a sound object playing and the second to stop a sound object from playing. */
//
// This function, when called will play the sound object
function EvalSoundPlay(soundobj) {
var thissound= eval("document."+soundobj);
thissound.Play();
}
// This function, when called will stop the sound object
function EvalSoundStop(soundobj) {
var thissound= eval("document."+soundobj);
thissound.Stop();
}
</script>

<!-- Functions Code Block End-->

<!-- Here we are embedding the sound file/s. We give each embedded sound a 'name' that we can refer to in a JavaScript event call.
-----
// Note: You can have multiple sounds embedded but remember that each sound requires a different 'name' and each would require its own set of play/pause buttons. -->

<embed src="father.mp3" autostart=false width=0 height=0 name="sound1" enablejavascript="true" />

<!-- This is an example of a second embedded sound. -->
<embed src="jingle_bell_rock.mp3" autostart=false width=0 height=0 name="sound2" enablejavascript="true" />

The following code creates a linked image that starts the sound:

<!-- Here we insert an image with a JavaScript event (onClick) and call our first function which plays the sound file defined above by 'name' -->

<img src="play.jpg" alt="Play button for sound1" border="0" onclick="EvalSoundPlay('sound1')" />

<!-- example of play button for a second embedded sound. -->
<img src="play.jpg" alt="Play button for sound2" border="0" onclick="EvalSoundPlay('sound2')" />

The following code creates a text link that pauses the sound:

<!-- Here we insert an image button with a JavaScript event (onClick) and call our second function which stops (pauses) the sound file playing -->

<img src="pause.jpg" alt="Pause button for sound1" border="0" onclick="EvalSoundStop('sound1')" />

<!-- example of a button for the second sound file. -->
<img src="pause.jpg" alt="Pause button for sound2" border="0" onclick="EvalSoundStop('sound2')" />

All of the sound and the image files (shown in red above) are in the same folder as the HTML page in my example code.

Play buttonPause button Father - MP3

Play buttonPause button Jingle Bell Rock - MP3

Home | HTML Help | Resources | Useful Links | Contact us