Different Ways to Play a Sound from a Web Page

Back to menu

5. Using a Background Sound and JavaScript

It is possible to do much the same as the above without the use of a hidden player if the browser supports the BGSOUND tag (in practice only Internet Explorer). Basically background sounds play as soon as the source sound is available; so the trick is to specify the source only in response to a JavaScript function. Here is the BGSOUND tag and the function:

    <bgsound id="sound">
    <script>
    function PlaySound(url) {
      document.all.sound.src = url;
    }
    </script>
    

Here are examples of a link, an image and a button calling the function.

    <a href="#" onMouseOver="PlaySound('success.wav')">Move mouse here</A>
    

    <img src="play.gif" onClick="PlaySound('success.wav')">
    

    <form>
    <input type="button" value="Play Sound" onClick="PlaySound('success.wav')">
    </form>
    

Compatibility: Internet Explorer, Firefox, Opera, Chrome.

Next method ...