在Javascript性能上播放声音很重吗?

cor*_*zza 2 javascript audio performance html5 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 about volume
        sounds[id].volume = vol;
    else
        sounds[id].volume = 1;

    sounds[id].play();
}
Run Code Online (Sandbox Code Playgroud)

我怎么称呼它:

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.
Run Code Online (Sandbox Code Playgroud)

在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;
Run Code Online (Sandbox Code Playgroud)

这完全消除了碰撞滞后,让我相信这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;
Run Code Online (Sandbox Code Playgroud)

而滞后又回来了!现在我确信播放声音会导致问题.我对么?为什么会这样?我如何解决它?

aps*_*ers 7

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

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

  2. <audio>为每个声音使用一个对象池,而不是为每种声音类型使用一个音频对象.而不是仅使用sounds[id],使用2D数组,访问sound[id][count].这里sound[id]是一个声音对象列表,它们都具有相同的声音,并且count是该声音id使用的当前对象的索引.每次调用时playSound(id),递增与该id相关联的计数,以便下一个调用调用不同的音频对象.

我不得不一起使用这些,因为播放暂停技术可以很好地将缓冲延迟移动到需要播放声音之前,但如果你需要快速播放声音,你仍然会得到延迟.这样,最近使用的音频对象可以在另一个对象播放时"充电".

  • 聪明,但也很难过必须这样做. (3认同)