【发布时间】:2012-04-22 03:16:09
【问题描述】:
我正在用 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;
延迟又回来了!现在我确定播放声音会导致问题。我对么?为什么会这样?我该如何解决?
【问题讨论】:
-
看起来 firefox 不支持 web 音频 api 以及 chrome/webkit - 你可能想尝试回退到一个 flash 插件,它可以在单独的进程/线程中播放声音(因此,不会阻止您的碰撞)
-
嗯...我有点反对,我认为 HTML5 应该完全取代 Flash,但是如果我必须...
-
我认为它也应该替换 Flash,但遗憾的是某些浏览器功能不太一致 :) 您可能需要确保在需要播放之前缓冲声音,例如使用 html
preload="auto"属性。
标签: javascript performance html audio html5-audio