我正在使用 JavaScript 和网络音频构建一个 Canvas 游戏。为了让它在 Firefox 中工作,我有一份 .ogg 格式的所有音频文件的副本。加载这些文件的代码如下。为了获得所需的音频文件,我使用 ' playSound(samplebb[3], channel1); ',我已经这样做了,因为在我的应用程序中,根据数字选择样本很有用,例如可以使用概率和随机性选择声音。
我在论坛上读到“加载器将接受 [mp3 和 ogg] 以获得相同的声音,只需在数组中传递两个路径而不是单个字符串。” 第四行代码是我尝试的,但它不起作用。
是否可以像这样为每个 mp3 加载备用 ogg 文件? (在一个缓冲区列表中)或者如果浏览器是 Firefox,我是否必须检测浏览器并构建 oggs 缓冲区列表?
谢谢
function loadSounds() {
bufferLoader = new BufferLoader(audioContext,
[
['sounds/1-KICK.mp3', 'sounds/1-KICK.ogg'], //0 // Not found
'sounds/2-BASS.mp3', //1
'sounds/3-BASS2.mp3', //2
'sounds/4-BASS4.mp3' //3
// ... ... ...
],
finishedLoading
);
bufferLoader.load();
}
function finishedLoading(bufferList) {
for (var i = 0, l = bufferList.length; i < l; i += 1) {
var source = audioContext.createBufferSource();
source.buffer = bufferList[i];
source.connect(audioContext.destination);
var note = {
note: source,
ready: true
};
samplebb.push(note);
}
setTimeout(play, 1000);
}
最佳答案
您是否使用BufferLoader
from html5rocks ?如果是这样,the JS file清楚地表明它只需要字符串(而不是数组)作为 url 参数。但是,您可以修改该类,使其按您想要的方式工作。请改用以下 BufferLoader.loadBuffer()
函数:
BufferLoader.prototype.loadBuffer = function(url, index) {
// Load buffer asynchronously
var request = new XMLHttpRequest(),
mult = typeof url != 'string',
srcInd = 0;
request.open("GET", mult ? url[srcInd++] : url, true);
request.responseType = "arraybuffer";
var loader = this;
request.onload = function() {
// Asynchronously decode the audio file data in request.response
loader.context.decodeAudioData(
request.response,
function(buffer) {
if (!buffer) {
if(!mult || srcInd == url.length) {
console.error('error decoding file data:', url);
return;
} else {
console.info('error decoding file data, trying next source');
request.open("GET", url[srcInd++], true);
return request.send();
}
}
loader.bufferList[index] = buffer;
if (++loader.loadCount == loader.urlList.length)
loader.onload(loader.bufferList);
},
function(error) {
if(!mult || srcInd == url.length) {
console.error('decodeAudioData error:', url);
return;
} else {
console.info('decodeAudioData error, trying next source');
request.open("GET", url[srcInd++], true);
return request.send();
}
}
);
}
request.onerror = function() {
if(!mult || srcInd == url.length) {
console.error('BufferLoader XHR error:', url);
return;
} else {
console.info('BufferLoader XHR error, trying next source');
request.open("GET", url[srcInd++], true);
return request.send();
}
}
request.send();
}
关于javascript - 网络音频加载 .mp3 和 .ogg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29924232/