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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17762763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:22:27  来源:igfitidea点击:

play .wav sound file encoded in base64 with javascript

javascripthtmlbase64

提问by Udo

Am able to play sound with javascript through the following,

能够通过以下方式使用 javascript 播放声音,

    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.

这会播放所需的声音,但有时加载速度很慢,甚至可能根本无法加载,因此我将声音编码为 base 64 并尝试以这种方式播放。

      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 ?

但声音不播放,有没有办法解决?

回答by Paul S.

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

这看起来不像是为HTMLAudioElement/使用Audio构造函数的正确方法。<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);

回答by Fong Kah Chun

var snd = new Audio("data:audio/x-wav;base64, <URI data>");
snd.play();

There is no need to declare splashas an object variable.

无需将splash声明为对象变量。

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

可以从以下位置轻松完成 Base64 转换:https: //dopiaza.org/tools/datauri/index.php