You are here: irt.org | FAQ | JavaScript | Sound | Q191 [ previous next ]
You should use the <embed> tag.
The following will play the midi or wav file as soon as its loaded:
<html> <body> <embed src="sound.wav" hidden=true> </body> </html>
The following allows you control when it plays:
<html>
<body>
<script language="JavaScript"><!--
function playSound() { if (navigator.mimeTypes["audio/x-wav"].enabledPlugin.name == "LiveAudio") document.firstSound.play(false); }
function pauseSound() { document.firstSound.pause(); }
function stopSound() { document.firstSound.stop(); }
//--></script>
<a href="javascript:playSound()">Play the sound now!</a><br>
<a href="javascript:pauseSound()">Pause/Restart the sound</a><br>
<a href="javascript:stopSound()">Stop the sound</a><br>
<embed src="sound.wav" hidden=true autostart=false loop=false name="firstSound" MASTERSOUND>
</body>
</html>You can replace sound.wav with sound.mid.
The above only works in Netscape. Here are two examples that works on most browsers, but if a user uses an incompatible plugin or activex you might still get errors.
Version 1: Netscape Navigator gets an embed and Internet Explorer gets an ActiveX:
<embed name="sound" src="h17bd.mid" hidden="true" autostart="false" MASTERSOUND>
<object id="sound" width="0" height="0" classid="CLSID:05589FA1-C356-11CE-BF01-00AA0055595A">
<param name="FileName" value="h17bd.mid">
<param name="PlayCount" value="1">
<param name="AutoStart" value="0">
<param name="ShowControls" value="0">
<param name="ShowDisplay" value="0">
</object>
<form>
<input type="button" value="Play" onClick="if (navigator.appVersion.indexOf('MSIE') !=-1) sound.Run(); if (navigator.mimeTypes["audio/x-wav"].enabledPlugin.name == "LiveAudio") document.sound.play(LOOP=1);">
<input type="button" value="Stop" onClick="if (navigator.appVersion.indexOf('MSIE') !=-1) sound.Stop(); else document.embeds["sound"].stop();">
</form>Version 2 (untested) Internet Explorer uses bgsound:
<bgsound id=objSound>
<embed name="sound" src="h17bd.mid" hidden="true" autostart="false" MASTERSOUND>
<form>
<input type="button" value="Play" onClick="if (navigator.appVersion.indexOf('MSIE') !=-1) objSound.src='http://www.server.com/midi/midi1.mid'; if (navigator.mimeTypes["audio/x-wav"].enabledPlugin.name == "LiveAudio") document.sound.play(LOOP=1);">
<input type="button" value="Stop" onClick="if (navigator.appVersion.indexOf('MSIE') !=-1) objSound.Stop(); else document.embeds['sound'].stop();">
</form>Marco Brandizi writes:
The stop statement seems not to workas Internet Explorer doesn't recognize objSound.Stop nor objSound.stop(). However, changing the src attribute to an empty string works:
<input type="button" value="Stop" onClick="if (navigator.appVersion.indexOf('MSIE') !=-1) objSound.src=''; else document.embeds['sound'].stop();">