Is Playing Sound In Javascript Performance Heavy?
Solution 1:
I ran into this same delay issue making a sound when the player fires a weapon. My solution was two-fold:
Play each sound at load time and then pause it immediately. This will allow it to resume playing quickly, rather than playing from scratch. Do this play-pause technique after every play of the sound.
Use a pool of
<audio>
objects for each sound, rather than a single audio object for each sound type. Instead of just usingsounds[id]
, use a 2D array, accessed withsound[id][count]
. Here,sound[id]
is a list of audio objects that all have the same sound, andcount
is the index of current object in use for that sound id. With each call toplaySound(id)
, increment the count associated with that id, so that the next call invokes a different audio object.
I had to use these together, because the play-pause technique does a good job of moving the buffering delay to before the sound needs to be played, but if you need the sound rapidly, you'll still get the delay. This way, the most recently used audio object can "recharge" while another object plays.
Solution 2:
Two things that might help you is to either utilize Web workers or to precompute several levels of loudness in advance, which you could also do in the background with worker threads. I'm saying this without going into the peculiarities of the Web audio API or how your computing the sound output, but if you've exhausted all other approaches this might be the next direction you should be focusing on.
Post a Comment for "Is Playing Sound In Javascript Performance Heavy?"