Playing Sound from JavaScript
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.
The browser will open a separate sound control window.
The user will then have to close this window manually.
Note that the script in Example 1 is not user-friendly:
every time the user clicks to run this script,
the browser will open a new sound control window -
even if there might be a couple of other audio windows already playing the same file!
Example 2.
Here's a more complex example in which you won't see a separate
sound control window. (You'll find a discussion below.)