且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 javascript 播放以 base64 编码的 .wav 声音文件

更新时间:2023-02-13 23:25:52

这看起来不像为 HTMLAudioElement/<audio>.

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

微调

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