Search code examples
javascriptaudiocross-browsercross-platformdhtml

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


I am writing a dhtml application that creates an interactive simulation of a system. The data for the simulation is generated from another tool, and there is already a very large amount of legacy data.

Some steps in the simulation require that we play "voice-over" clips of audio. I've been unable to find an easy way to accomplish this across multiple browsers.

Soundmanager2 comes pretty close to what I need, but it will only play mp3 files, and the legacy data may contain some .wav files as well.

Does anyone have any other libraries that might help?


Solution

  • 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);
        }
    //======================================================================