Stephen Kellett wrote:
Hi Folks,
How can I play midi and/or audio files using JavaScript?
I have never seen a satisfactory answer to playing sound files
interactively, so here's my solution:
<html>
<body>
<!--
If available, copy the Windows .wav files: blip ding & chimes into the
same folder as this file, or substitute your own.
Files play on mouseover and abort on mouseout
-->
<a href='#'>Blip</a> - <a href='#'>Ding</a> - <a href='#'>Dumb</a> - <a
href='#'>Dumb</a> - <a href='#'>Chime</a>
<script type='text/javascript'>
/*
* Sound File Player (C)2006 Stephen Chalmers
*
* Donations to:
http://www.hotspot.freeserve.co.uk/luv2payu/
*
*/
function SCmediaPlay(sou ndFile)
{
this.soundFile= soundFile;
this.objRef=nul l;
this.preLoad();
}
SCmediaPlay.pro totype.removeOb j=function()
{
if(this.objRef! =null)
{
document.body.r emoveChild(this .objRef);
this.objRef=nul l;
}
}
SCmediaPlay.pro totype.playSoun d=function()
{
this.removeObj( );
this.objRef=doc ument.createEle ment('embed');
this.objRef.set Attribute("widt h","0");
this.objRef.set Attribute("heig ht","0");
this.objRef.set Attribute("hidd en","true");
this.objRef.set Attribute("src" , this.soundFile) ;
document.body.a ppendChild(this .objRef);
}
SCmediaPlay.pro totype.preLoad= function() /* preloads the associated
plugin & possibly the media file also */
{
document.write( "<embed src='"+this.sou ndFile+"' hidden='true'
autostart='fals e' width='0' height='0'>");
/* Opera won't recognise autostart using creatElement */
}
if(document.bod y && document.create Element)
{
/* == CONFIGURATION ==
*
* Populate the object table below with your own filenames and link
indices.
* Preserve the syntax as shown.
*
* ind == the zero-based index of the link that plays a sound.
*
* f == the file to be played by the corresponding link (remember to
add a relative
* path if needed)
*
*/
var SCmediaTable=[ {ind: 0, f: 'blip.wav' },
{ind: 1, f: 'ding.wav' },
{ind: 4, f: 'chimes.wav'}
];
var SCobjTable=[];
for(var i=0; i<SCmediaTable. length; i++)
{
SCobjTable[i]=new SCmediaPlay(SCm ediaTable[i].f)
document.links[ SCmediaTable[i].ind ].onmouseover=
new Function("SCobj Table["+i+"].playSound()") ;
document.links[ SCmediaTable[i].ind ].onmouseout=
new Function("SCobj Table["+i+"].removeObj()") ;
}
}
</script>
</body>
</html>