29
votes

Am able to play sound with javascript through the following,

    var snd = new Audio('sound.wav');
    snd.play();

This plays the required sound but sometimes it loads slowly or might not even load at all so i encoded the sound in base 64 and tried to play it this way.

      var splash = {
prefix: "data:audio/wav;base64,",
sound: [ "*base64 string here*" ] };

    var snd = new Audio(splash); 
    snd.play();

but the sound does not play, is there a way around it ?

2
You did what now? Why would you encode the audio as base64 ! - adeneo
so that it would play faster, i saw it done in a plugin, google fart scroll - Udo
In 2018, it seems that Chrome doesn't support playing WAVs this way. If you snd.play().catch(err=>console.log(err)) you will see: "NotSupportedError: The element has no supported sources." The solution for me was to use mp3s instead of wavs. The link provided by @Fong-Kah-Chun to generate the string to pass to new Audio works great btw. - imjosh

2 Answers

61
votes

That doesn't look like the correct way to use the Audio constructor for HTMLAudioElement / <audio>.

Slight adjustment

var snd = new Audio("data:audio/wav;base64," + base64string);
snd.play();

If it works in console but not in script, it may be getting garbage collected, in which case scope it so it will stay

var Sound = (function () {
    var df = document.createDocumentFragment();
    return function Sound(src) {
        var snd = new Audio(src);
        df.appendChild(snd); // keep in fragment until finished playing
        snd.addEventListener('ended', function () {df.removeChild(snd);});
        snd.play();
        return snd;
    }
}());
// then do it
var snd = Sound("data:audio/wav;base64," + base64string);
10
votes
var snd = new Audio("data:audio/x-wav;base64, <URI data>");
snd.play();

There is no need to declare splash as an object variable.

Base64 conversion can be done easily from: https://dopiaza.org/tools/datauri/index.php