Play Sound Using JavaScript

No matter what I do, I just can't get it to play sound in Firefox or IE or Chrome, for that matter.

<html>
<head>
<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);

     document.childNodes[0].appendChild(embed);

 }

// -->
</script>
</head>
<body onload="play();">
</body>
</html>
+2
source share
3 answers

Try using this revised version of the play () function

function play() 
{
  var embed=document.createElement('object');
  embed.setAttribute('type','audio/wav');
  embed.setAttribute('data', 'c:\test.wav');
  embed.setAttribute('autostart', true);
  document.getElementsByTagName('body')[0].appendChild(embed);
}

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

If you are trying to get more compatibility from this, you should also consider adding an embed tag as an alternative to an object tag. The way it works is as follows:

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

noscript, , , embed.

+6

, :

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;
        else
            a.src = soundfile_mp;

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

, :

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

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

0
source

All Articles