Published: Sunday, October 11, 1998
Playing a Sound using JavaScript in Response to an Event
Have you ever wanted to play a sound when a user performed a certian action? This is
not too difficult to do using JavaScript. What you need to do first, is embed your sound.
You can do that by using the following code:
<EMBED NAME="MySound" SRC="MyWavFile.wav" AUTOSTART="false"
HIDDEN="true">
To play the sound, employ the following function:
<SCRIPT LANGUAGE="JavaScript">
var bolDocumentLoaded = false;
function PlaySound(mySound) {
if (bolDocumentLoaded) {
if (navigator.appName = "Netscape")
document.embeds[mySound].play(false);
else
document.embeds[mySound].Run();
}
}
</SCRIPT>
You'll notice that we don't want to let the sound be played until the entire document is
loaded. This ensures that we have fully downloaded the sound before trying to play it.
To let JavaScript know that we've finished downloading the page, we need to code for the
ONLOAD event. You will want to add this simple line inside your BODY tag:
<BODY ONLOAD="bolDocumentLoaded=true;">
Finally, to get the sound to play you just need to make a call to PlaySound, passing in
the sound you want to play. So, if we had a button that you wanted to have a sound played
when clicked, you could write this:
<FORM>
<INPUT TYPE="BUTTON" NAME="btnSoundButton" ONCLICK="PlaySound('MySound');">
</FORM>
Happy Programming!