我目前正在使用 Javascript 和 Cordova 框架开发和测试一款 iOS 游戏。我试图在触摸某些节点时添加声音效果。由于节点可以以任何速率重复触摸。我正在使用...
var snd = new Audio("audio/note_"+currentChain.length+".mp3");
snd.play();
这可以满足我的需要,但是当我启用这些效果时,我发现游戏滞后。我正在处理大小已缩小至约 16kb 的 mp3 文件,但延迟仍然很大。
在我的情况下优化声音的最佳方法是什么?由于该应用程序不是 native 的,我的质量是否受到限制?
谢谢!
最佳答案
最好的选择是预加载它们并在需要时准备好。我刚刚写了一个快速的独立闭包,我认为它会向您展示您想知道如何做的大部分内容。
var playSound = (function () {
var sounds = 15, // idk how many mp3 files you have
loaded = new Array(sounds),
current = -1,
chain = [],
audio,
i;
function incrementLoaded(index) {
loaded[index] = true;
}
// preloads the sound data
for(i = 0; i < sounds; i++) {
audio = new Audio();
audio.addEventListener('canplay', incrementLoaded.bind(audio, i));
audio.src = 'audio/note_' + i + '.mp3';
chain.push(audio);
}
// this will play audio only when ready and in sequential order automatically
// or "which" index, if supplied
return function (which) {
if(typeof which === 'number') {
current = which;
} else {
current = (current + 1) % sounds;
}
// only play if loaded
if(loaded[current]) {
chain[current].pause();
chain[current].currentTime = 0;
chain[current].play();
}
};
}());
// would play sounds in order every second
setInterval(function () {
playSound();
}, 1000);
关于javascript - 优化 iOS Web App 的音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27894835/