Javascript 播放声音性能重吗?

2024-05-20

我正在用 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;

延迟又回来了!现在我确信播放声音会引起问题。我对么?为什么会发生这种情况?我如何解决它?


我遇到了同样的延迟问题,当玩家发射武器时发出声音。我的解决方案有两个:

  1. 在加载时播放每个声音,然后立即暂停。这将允许它快速恢复播放,而不是从头开始播放。每次播放声音后都执行此播放暂停技巧。

  2. 使用池<audio>每种声音的对象,而不是每种声音类型的单个音频对象。而不是仅仅使用sounds[id],使用二维数组,通过以下方式访问sound[id][count]。这里,sound[id]是具有相同声音的音频对象的列表,并且count是该声音 ID 使用的当前对象的索引。每次致电playSound(id),增加与该 id 关联的计数,以便下一次调用调用不同的音频对象。

我必须将它们一起使用,因为播放暂停技术可以很好地将缓冲延迟移至before需要播放声音,但如果您需要快速播放声音,您仍然会遇到延迟。这样,最近使用的音频对象可以在另一个对象播放时“充电”。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Javascript 播放声音性能重吗? 的相关文章

随机推荐