Playing Sound from JavaScript

JavaScript FAQ | JavaScript Sound FAQ  

Question: How do I write a JavaScript function that plays a sound file?

Answer: There are different ways to play sound from JavaScript. Let's consider a couple of examlpes.

Example 1. Here's the simplest cross-browser script for playing a sound file:
self.location="AUDIO_FILE_URL"

Click here to test the code of Example 1. Most modern browsers will close the current page in the active browser window or tab, and replace it with a sound control. Some older browsers used to open a separate sound control window (even though self.location in the script code is supposed to instruct the browser to use the current window or tab). In either case, the script in Example 1 is not user-friendly: most users won't appreciate losing the page they are reading - nor would they particularly like additional sound control windows!

Example 2. Here's a more complex example in which you won't see a separate sound control window. (You'll find discussion and source code below.)

In Microsoft Internet Explorer, there are several ways to play a sound file from JavaScript, without opening a separate window for sound control. For example, you can use the Explorer-specific BGSOUND tag:
<BGSOUND ID="BGSOUND_ID" LOOP=1 VOLUME="-600" SRC="jsilence.mid">
Use the following JavaScript code to play a sound file mySound.mid via the BGSOUND tag:
To start playing: document.all['BGSOUND_ID'].src='mySound.mid'
To stop playing: document.all['BGSOUND_ID'].src='jsilence.mid'
Here mySound.mid stands for the name of the sound file that you actually want to play; jsilence.mid is a "do-nothing" sound file - it does not play any sound at all, but can be used to stop the playback of other sound files.

In Netscape Navigator, you had to use the LiveAudio plugin and put an EMBED tag on your page. For example, to play the file mySound.mid and hide the LiveAudio window, you could use the following EMBED tag:

<EMBED NAME="mySound" SRC="mySound.mid" 
LOOP=false AUTOSTART=false HIDDEN=true MASTERSOUND>
In Netscape Navigator 4.x, the NAME of the EMBED tag was used to control the audio playback from JavaScript; for example, a JavaScript call document.mySound.stop() would stop the playback of the current audio file. Most modern brosers support the EMBED tag too; however, the tag is no longer scriptable in most configurations (e.g. document.mySound.stop() no longer works) and the tag itself is now considered obsolete - instead of EMBED, use the OBJECT tag (see below).

In Firefox, Safari, and Google Chrome the audio playback functionality relies on plugins such as Apple QuickTime. With the audio plugin(s) installed, you will need an OBJECT tag for the browser to activate the plugin. Here is an example of an OBJECT tag:

<OBJECT DATA="audioURL.mid" TYPE="audio/midi" 
        TITLE="Description" WIDTH=250 HEIGHT=20>
  <PARAM NAME=autostart VALUE=true>
  <PARAM NAME=hidden VALUE=false>
</OBJECT>

The Opera browser now supports all of the above tags: OBJECT, EMBED, and even BGSOUND (although BGSOUND in Opera cannot be manipulated from JavaScript, e.g. document.getElementById('BGSOUND_ID').src='anotherURL.mid' won't work here).

The source code of Example 2 is shown below. If the user has Internet Explorer, the code relies on the BGSOUND technique described above. In browsers other than Internet Explorer, the code expects that the current browser window has an IFRAME named iplayer. The IFRAME is used to display the HTML markup of the object/plugin responsible for playing the audio file; all the other content of the current page remains intact when the playback starts or stops. There are two simple JavaScript functions playSound() and stopSound() that actually start and stop the playback.

<BGSOUND id="BGSOUND_ID" LOOP=1 SRC="jsilence.mid">

<script type="text/javascript" language="JavaScript">
<!--
function playSound(audioURL) {
 if (document.all) document.all['BGSOUND_ID'].src=audioURL;
 else self.iplayer.location.replace('jsplayer.htm?'+audioURL);
}

function stopSound() {
 if (document.all) document.all['BGSOUND_ID'].src='jsilence.mid';
 else self.iplayer.location.replace('jsplayer.htm?stop');
}
//-->
</script>

<form name=myform>
<input type=button value="Play Sound" onClick="playSound('Bach.mid')">
<input type=button value="Stop Sound" onClick="stopSound()">
</form>
The helper page jsplayer.htm?audioURL.mid is used to overcome security warnings regarding the same-origin policy violations that might occur if we tried to display an audioURL from another domain in our IFRAME directly, and then use self.iplayer.location.replace to further change the audioURL location. The javascript code in jsplayer.htm sniffs the browser and renders HTML for the playback of audioURL.mid (which can be a relative URL like audioURL.mid or an absolute URL like http://javascripter.com/audioURL.mid).

Copyright © 1999-2011, JavaScripter.net.