Cross-platform, cross-browser way to play sound from Javascript? [duplicate]

You will have to include a plug-in like Real Audio or QuickTime to handle the .wav file, but this should work…

//======================================================================
var soundEmbed = null;
//======================================================================
function soundPlay(which)
    {
    if (!soundEmbed)
        {
        soundEmbed = document.createElement("embed");
        soundEmbed.setAttribute("src", "/snd/"+which+".wav");
        soundEmbed.setAttribute("hidden", true);
        soundEmbed.setAttribute("autostart", true);
        }
    else
        {
        document.body.removeChild(soundEmbed);
        soundEmbed.removed = true;
        soundEmbed = null;
        soundEmbed = document.createElement("embed");
        soundEmbed.setAttribute("src", "/snd/"+which+".wav");
        soundEmbed.setAttribute("hidden", true);
        soundEmbed.setAttribute("autostart", true);
        }
    soundEmbed.removed = false;
    document.body.appendChild(soundEmbed);
    }
//======================================================================

Leave a Comment