问题描述
我可以通过以下方式使用 javascript 播放声音,
Am able to play sound with javascript through the following,
var snd = new Audio('sound.wav');
snd.play();
这会播放所需的声音,但有时加载速度很慢,甚至可能根本不加载所以我用 base 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 ?
推荐答案
这看起来不像为 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);
这篇关于使用 javascript 播放以 base64 编码的 .wav 声音文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!