play .wav sound file encoded in base64 with javascript

后端 未结 2 1562
谎友^
谎友^ 2020-11-28 06:08

Am able to play sound with javascript through the following,

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

This plays the require

相关标签:
2条回答
  • 2020-11-28 06:42

    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);
    
    0 讨论(0)
  • 2020-11-28 06:45
    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

    0 讨论(0)
提交回复
热议问题