在使用JavaScript的base64播放.wav声音文件连接codeD [英] play .wav sound file encoded in base64 with javascript

查看:3622
本文介绍了在使用JavaScript的base64播放.wav声音文件连接codeD的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够通过以下使用JavaScript播放声音,

Am able to play sound with javascript through the following,

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

本播放所需的声音,但有时加载缓慢或可能甚至不加载所有
所以我带$ C $光盘基地64的声音,并试图通过这种方式进行播放。

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 ?

推荐答案

这看起来并不像正确的方式使用的音频的构造函数<一个href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement\">HTMLAudioElement / <一个href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio\"><$c$c><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);

这篇关于在使用JavaScript的base64播放.wav声音文件连接codeD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆