Play sounds using javascript on the fly

I was having some trouble getting sounds to play dynamically using javascript today. I’m not sure dynamically is the right word but basically I wanted different sounds to load and play on the click of a button using javascript without having to preload the sounds.

At first I tried using a single embed object, then changing the src of the embed on a button click and using embedObj.Play(); but for some reason changing the source of the file stopped that happening.

My second idea was to replace the entire embed code each time, and then call Play on the embed to get it to play. Still no luck!

Finally after a bit of searching I found somebody that had managed to do it. Its similar to my second idea only instead of calling .Play() on the embed object you just use autostart=true in the embed code, simple!

This is the code I ended up using, it requires WMP which was fine for my needs but I’m sure it could be rewritten to not be so picky.

<script type"text/javascript">
function PlayMedia(fileName){
document.getElementById("player").innerHTML='<object id="mediaPlayer" width="320" height="240" '
+'classid="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95" '
+'codebase=",1,52,701" '
+'standby="Loading Microsoft Windows Media Player components..." type="application/x-oleobject">'
+'<param name="fileName" value="'+fileName+'">'
+'<param name="autoStart" value="true">'
+'<param name="showControls" value="true">'
+'<param name="ShowStatusBar" value="1">'
+'<param name="loop" value="false">'
+'<embed type="application/x-mplayer2" '
+'pluginspage="" '
+'showcontrols="true" width="0" height="0" '
+'src="'+clipName+'" autostart="true" loop="false">'

Just send it the file location as the first parameter and remember to include an element on your page with an id of ‘player’ (in this case), like so:

<div id="player"></div>