Playing sound with JavaScript

Doesn't matter what I do, I simply can't get this to play a sound in Firefox or IE, or Chrome for that matter.

<script type="text/javascript">

    function play() 
     var embed = document.createElement('object');

     embed.setAttribute('src', 'c:\\test.wav');
     embed.setAttribute('hidden', true);
     embed.setAttribute('autostart', true);
     embed.setAttribute('enablejavascript', true);



// -->
<body onload="play();">



Try using this revised version of the function play()

function play() 
  var embed=document.createElement('object');
  embed.setAttribute('data', 'c:\test.wav');
  embed.setAttribute('autostart', true);

The problem with your code was you were using the src attribute, which is for the <embed> tag. Instead, use the data attribute for the <object> tag.

If you are trying to get the most compatibility out of this, you should also consider adding the embed tag as an alternate for the object tag. The way it works is like this:

<object data="test.wav" type="audio/wav" autostart="true">
<embed src="test.wav" autostart="true" alt="Could not load audio" />

This works similar to the noscript tag, where older browsers that don't support the object tag resort to the embed tag.


Try This Method, to play sound in all your browsers :

function playSound(soundfile_ogg, soundfile_mp, soundfile_ma) {
    if ("Audio" in window) {
        var a = new Audio();
        if (!!(a.canPlayType && a.canPlayType('audio/ogg; codecs="vorbis"')
                .replace(/no/, '')))
            a.src = soundfile_ogg;
        else if (!!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/,
            a.src = soundfile_mp;
        else if (!!(a.canPlayType && a.canPlayType(
                'audio/mp4; codecs="mp4a.40.2"').replace(/no/, '')))
            a.src = soundfile_ma;
            a.src = soundfile_mp;

        a.autoplay = true;
    } else {
        alert("Time almost up");

to play the sound, do something like this:

playSound("/file/horse.wav", "/file/horse.mp3","/file/horse.m4a");

FYI using the <embed> tag will invalidate your code. At the moment you have two choices if you want to play sounds on your web page: [1] use the method which works on most browsers today, but which will invalidate your HTML (using <embed>), or [2] use the methods which will only work in some of the latest browsers, but which will be the way to go in the future and also is considered valid HTML (using <audio> or <object>).


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.