我正在用 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 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;
延迟又回来了!现在我确定播放声音会导致问题。我对么?为什么会这样?我该如何解决?
最佳答案
我遇到了同样的延迟问题,当玩家开火时发出声音。我的解决方案有两个方面:
在加载时播放每个声音,然后立即暂停。这将使它能够快速恢复播放,而不是从头开始播放。在每次播放声音后执行此播放暂停技巧。
使用
<audio>
的池每个声音的对象,而不是每个声音类型的单个音频对象。而不是仅仅使用sounds[id]
,使用二维数组,通过sound[id][count]
访问.在这里,sound[id]
是所有具有相同声音的音频对象的列表,count
是用于该声音 ID 的当前对象的索引。每次调用playSound(id)
,增加与该 ID 关联的计数,以便下一次调用调用不同的音频对象。
我必须同时使用它们,因为播放暂停技术可以很好地将缓冲延迟移动到需要播放声音之前,但是如果您需要快速播放声音,您仍然会延迟。这样,最近使用的音频对象可以在另一个对象播放时“充电”。
关于javascript - 在 Javascript 中播放声音性能很重吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10078463/