Highlights
All Snippets
Top 100 Snippets
Librarians
gbCodeLib

By Language
VB6
JavaScript
Perl
HTML
SQL
Java
DOS

GBIC >> Source Code >> JavaScript >> Snippet

Play a sound file


/* 1st Method */
Make the embedded player hidden and control it from JavaScript.
There are two parts to this : firstly a function (here called EvalSound)
which takes the "name" of the hidden embedded player and calls its
Play() method. Secondly a link, image or button which calls the function
on demand when the component is clicked or has the mouse rolled onto it.

< script >
function EvalSound(soundobj) {
  var thissound = eval ( "document." + soundobj);
 thissound.Play();
}
</ script >

/* embed a player and make it hidden */
< embed src = "success.wav" autostart = false hidden = true name = "sound1" enablejavascript = "true" >

/* mouseover to play sound */
< a href = "#" onMouseOver = "EvalSound('sound1')" > Move mouse here </ A >
/* click image to play sound */
< img src = "play.gif" onClick = "EvalSound('sound1')" >
/* press button to play sound */
< form >< input type = "button" value = "Play Sound" onClick = "EvalSound('sound1')" ></ form >


/* 2nd Method */
Use the JavaScript getElementById() function in the EvalSound definition.
< script >
function EvalSound(soundobj) {
  var thissound = document.getElementById(soundobj);
 thissound.Play();
}
</ script >

< embed src = "success.wav" autostart = false hidden = true id = "sound1" enablejavascript = "true" >
Note that we specify name of the embedded sound using its ID attribute now. The function calls however are the same as above. For example :

/* mouseover to play sound */
< a href = "#" onMouseOver = "EvalSound('sound1')" > Move mouse here </ A >
/* click image to play sound */
< img src = "play.gif" onClick = "EvalSound('sound1')" >
/* press button to play sound */
< form >< input type = "button" value = "Play Sound" onClick = "EvalSound('sound1')" ></ form >