WWW FAQs: How do I play sound from JavaScript?

2006-11-21: Playing sound from JavaScript used to be difficult and frustrating. Now it's easy, thanks to a nifty new Flash-based solution. And no, you do not have to own Flash to take advantage of this method. I'll explain how to do it step by step. But first, let me explain why we need Flash to solve this problem properly.

Why We Can't Do It The Old Way

Playing sound from JavaScript has traditionally been difficult, due to wildly different behavior among the various audio players. Designers could embed an audio player with the embed element, which offers an enablejavascript attribute. But there was no way to tell which audio player was present, if any. There was no way to tell whether it supported JavaScript. And there was no way to tell if it supported the sort-of-standard Start, Stop, and Play methods, let alone anything else (hint: most of them didn't support anything else).

Still, you could suffer through and make this mostly work - until recently, when Microsoft released Internet Explorer 7 for Windows. IE7 for Windows, which will soon be standard equipment on new computers sold with Windows Vista, displays a small warning message and does not play sounds triggered by JavaScript unless the user goes out of their way to approve doing that. Which most people will not do.

So the old-fashioned way of playing sound from JavaScript is pretty much dead for those of us who want to design websites the general public can use.

Solving It With Flash... Without Buying Flash

Flash developers, on the other hand, have it easy. They have total control over audio effects in their Flash movies. And Flash works in all of the major web browsers, on all of the major operating systems. If only we could access this power from JavaScript code in a web page... wait a minute, we can!

Scott Schiller has released an excellent, free Flash-based player component designed expressly for those who want to play sounds from JavaScript - and yes, I do mean "real" JavaScript in your web page responding to mouse-over events, timers, page load events, and so on. I'm not talking about ActionScript in a Flash movie.

In fact, there is no Flash player visible on your page when you use Scott Schiller's SoundManager. Once you have installed SoundManager on your website, all you have to do is write a simple XML file with your favorite text editor, such as Notepad, in which you'll define your sounds. Then, in your web page, you load SoundManager with a simple <script src> element, and play sounds whenever you like with easy JavaScript calls like soundManager.play(label).

Are You Sure I Don't Have To Buy Flash?

Yes. Schiller has already created a finished Flash-based player which you can configure to play the sounds you want. There is no need to own your own copy of Flash to take advantage of this.

Which browsers does SoundManager support?

In my tests, SoundManager works great with:

1. Internet Explorer for Windows (all tested versions, including 7)

2. Firefox for Windows, Linux, and MacOS X

3. Safari 2.0 or better, for current versions of MacOS X

4. Opera for Windows

SoundManager does not work with:

1. Opera for MacOS X

2. Safari 1.x for older versions of MacOS X

In most cases, the occasional browser that can't use SoundManager would not work with the old-fashioned method of controlling sound from JavaScript either. So there's really no reason to "fall back" to the embed element.

How To Use SoundManager In Your Page

OK, I've convinced you - so how do you use SoundManager?

Just follow these steps to get started:

1. Visit the SoundManager page.

2. Click on the download link to obtain the SoundManager zip file.

3. Extract the zip file to your website, or to a test website on your own computer. Do this in a new sub-folder called SoundManager. Do not crush your own index.html file!

If you try to open SoundManager-based pages as local files, instead of via a website, you will get warnings from your web browser. This does not happen when you move them to a real website. Follow the browser's recommended steps to allow the files to play, or just test your pages on a test web server running on your own computer.
4. The SoundManager zip file includes a page called basic-example.html. Visit that page with your browser and experiment with the buttons. If you have correctly extracted the zip file you should be able to control the sound by clicking on ordinary HTML form buttons.

5. Move the file soundcontroller.swf to the folder where you would like to have your own sound-enabled web page. Also move the file soundmanager.js from the script sub-folder into the folder containing the page you want to add JavaScript sounds to.

6. Decide what sounds you will use. Convert those sounds to MP3 format, if you haven't already. Upload them to a new subfolder called audio within the folder where your page will be.

7. With a text editor, such as Windows Notepad, create a simple XML file defining your sounds. For each sound, you'll specify the URL where it can be loaded and an id by which you'll refer to it later.

In this example, I am assuming that you have two sounds, in files called on.mp3 and off.mp3, and that you put your sounds in a subfolder called audio as I described in step 6:

<?xml version="1.0" encoding="UTF-8"?>

<items baseHref="audio/" defaultVol="100">

<sound id="on" href="on.mp3" />
<sound id="off" href="off.mp3" />


8. Save this XML file under the name sound-config.xml. Make sure the file is saved under that name, and not as sound-config.txt, sound-config.xml.txt or any other name. Rename the file from Windows Explorer if you have to, this is important.

9. Move sound-config.xml to the website folder where your web page will be. This is the same folder where you have already placed soundcontroller.swf.

10. Edit your HTML page. In the head section of your page, add these two lines to import the sound manager:

<script type="text/javascript" src="soundmanager.js">

11. In any JavaScript code you wish, such as the onClick handler of a button or the onMouseOver handler of an image, play a sound by calling the play function with one of the sound IDs you set up in sound-config.xml.

Here's a simple example. Assuming you have an image called myimage.gif and that you defined a sound with the ID on in sound-config.xml, this code will play the on sound when you move the mouse over the image:

<img src="myimage.gif"
  onMouseOver="soundManager.play('on')" />

12. Required: make sure your page has at least one div element. I know it's strange, but it's necessary. Schiller's code inserts certain elements after the first div in the page and will break if you don't have any. Most interesting web pages have lots of div elements, but if you're making a simple example page, just put an empty div at the end:


And that will take care of the problem just fine.

13. Important! Just before the close of your body element, you must call soundManagerInit, like this:


Note: this call must come after at least one div element in the page. So put it right before </body> and you'll be safe.

If you don't do this, your sounds won't work. So don't forget!


Here's an example of a very simple web page that uses SoundManager. Keep in mind that all of the supporting files must be in the right places for this to work:

<script type="text/javascript" src="soundmanager.js">
<img src="myimage.png"
<!-- Must have at least one div,
  BEFORE calling soundManagerInit! -->

This page plays the sound with the ID "on" when the mouse moves over the image.

If It Doesn't Work

Did you:

1. Download the SoundManager zip file?

2. Move soundcontroller.swf and soundmanager.js to the folder containing the page you plan to add sound to?

3. Create a sound-config.xml file, name that file correctly, and move it to the folder containing the page you plan to add sound to?

4. Remember to load soundmanager.js in the head element of your page?

5. Call soundManager.play with a sound ID that you defined in your sound-config.xml file?

6. Upload your sounds to the audio subfolder correctly?

7. Convert those sounds to MP3 format correctly, if they were not already MP3 files?

8. Remember to call soundManagerInit just before the </body> tag of your page?

9. Make sure your page has at least one div element?

Follow these troubleshooting steps and you should be in good shape.

If Your Sounds Play Too Fast

Do your MP3 files sound like chipmunks playing with helium balloons? Some MP3 files are not compatible with Flash Player. Fortunately this is easy to fix. See the article why do my MP3 files sound bad in Flash Player? for the solution.

Advanced Tricks

That's it for the basics! Of course, SoundManager can do quite a bit more. You can cause a song to loop by specifying a number of repetitions in the play call:

soundManager.play('on', 100); // Plays 100 times

And you can stop the playback of a sound at any time with the stop call:


Finally, you can adjust the volume with the setVolume call:

soundManager.setVolume('on', 50); // 50% of maximum

For more information about SoundManager, check out the SoundManager home page.

Legal Note: yes, you may use sample HTML, Javascript, PHP and other code presented above in your own projects. You may not reproduce large portions of the text of the article without our express permission.

Got a LiveJournal account? Keep up with the latest articles in this FAQ by adding our syndicated feed to your friends list!