在Javascript中播放声音的性能是否很高?
我正在用Javascript制作一个简单的游戏,当一个对象与墙碰撞时,它会发出“砰”的声音。声音的响度取决于物体的速度(速度越高=>声音越大) 播放功能:在Javascript中播放声音的性能是否很高?,javascript,performance,html,audio,html5-audio,Javascript,Performance,Html,Audio,Html5 Audio,我正在用Javascript制作一个简单的游戏,当一个对象与墙碰撞时,它会发出“砰”的声音。声音的响度取决于物体的速度(速度越高=>声音越大) 播放功能: playSound = function(id, vol) //ID of the sound in the sounds array, volume/loudness of the sound { if (vol) //sometimes, I just want to play the sound without worrying
playSound = function(id, vol) //ID of the sound in the sounds array, volume/loudness of the sound
{
if (vol) //sometimes, I just want to play the sound without worrying about volume
sounds[id].volume = vol;
else
sounds[id].volume = 1;
sounds[id].play();
}
我如何称呼它:
playSound(2, Math.sqrt(p.vx*p.vx + p.vy*p.vy)/self.TV); //self.TV stands for terminal velocity. This calculates the actual speed using the basic Pythagora's theorem and then divides it by self.TV, which results in a number from 0 to self.TV. 2 is the id of the sound I want to play.
在Chrome中,一切都很好。不过,在Firefox中,每次与墙壁发生碰撞(=>playSound
被调用),都会有一个持续近半秒的暂停!起初,我以为问题出在Math.sqrt
,但我错了。我就是这样测试的:
//playSound(2, 1); //2 Is the id of the sound I want to play, and 1 is max loudness
Math.sqrt(p.vx*p.vx + p.vy*p.vy)/self.TV;
Math.sqrt(p.vx*p.vx + p.vy*p.vy)/self.TV;
Math.sqrt(p.vx*p.vx + p.vy*p.vy)/self.TV;
这完全消除了冲突延迟,并使我相信Math.sqrt
根本没有引起任何问题。不过,为了确保这一点,我做到了:
playSound(2, 1); //2 Is the id of the sound I want to play, and 1 is max loudness
//Math.sqrt(p.vx*p.vx + p.vy*p.vy)/self.TV;
//Math.sqrt(p.vx*p.vx + p.vy*p.vy)/self.TV;
//Math.sqrt(p.vx*p.vx + p.vy*p.vy)/self.TV;
而滞后又回来了!现在我确信播放声音会引起问题。我说得对吗?为什么会这样?如何修复它?我遇到了同样的延迟问题,当玩家发射武器时会发出声音。我的解决方案有两个方面:
对象池,而不是为每个声音类型使用单个音频对象。不要只使用sounds[id]
,而是使用一个2D数组,通过sound[id][count]
访问。这里,sound[id]
是所有具有相同声音的音频对象的列表,count
是该声音id当前使用对象的索引。每次调用playSound(id)
,增加与该id相关联的计数,以便下一次调用调用不同的音频对象我必须同时使用它们,因为播放暂停技术很好地将缓冲延迟移动到需要播放声音之前,但是如果您需要快速播放声音,您仍然会得到延迟。通过这种方式,最近使用的音频对象可以在另一个对象播放时“充电”。有两件事可以帮助您提前利用或预计算几个音量级别,您也可以在后台使用工作线程来完成。我这样说并没有讨论Web音频API的特性,也没有讨论如何计算声音输出,但是,如果您已经用尽了所有其他方法,这可能是您应该关注的下一个方向。看起来firefox不支持web音频API以及chrome/webkit-您可能想尝试使用flash插件,它可以在单独的进程/线程中播放声音(因此,不会阻止冲突),嗯。。。我有点反对,我认为HTML5应该完全取代Flash,但如果必须的话……我认为它也应该取代Flash,但遗憾的是,某些浏览器功能的一致性要差得多:)你可能需要确保在播放声音之前先缓冲声音,比如html
preload=“auto”
attribute。使用web workers进行预计算有什么意义?如果只完成一次,那么它也可以在主线程中执行。