Managing sounds in HTML5 games and playing multiple instances of a sound in javascript

One thing I had trouble with in my development of a game for HTML5′s canvas was playing multiple instances of a sound. When I tried googling for answers, I pretty much just got results from people saying “just embed an audio element in the page” or “just replay the sound lol.” My problem was that the sound wouldn’t replay until it’d completed, which is awful when you want to trigger it rapidly, e.g., a chain of explosions or bullet fire. Simply doing sound.play() wouldn’t do the job.

Then I realized the solution is stupidly simple: use that handy “currentTime” variable that’s bound to every javascript Audio object and just reset it, and manage all sounds with an associative array.

Now if you want to play “smallexpl”, just do a playSound("smallexpl");

While it doesn’t play multiple instances of a sound at once, it allows it to be rapidly retriggered and is good enough for most games.

If you insist on playing multiple instances concurrently, you could probably do something like this (not real code below, but should be easily understood):

//For each sound, we'll want an array of duplicates
//The number of duplicates is the number you can play concurrently
var sounds = {"snd1":[new Audio("snd1.ogg"), new Audio("snd1.ogg"), etc], "snd2":[new Audio("snd2.ogg"), more duplicates, etc]};
i = 0

//Now the below pseudocode would be inserted wherever you want to play 'snd1'
//We'll increment i to go to the next item in the list of duplicates
if (!sounds["snd1"][i].ended)
//play sound 'name' at index i++
if (i > sounds["snd1"].length)
i = 0

In Firefox at least you can simply clone the audio node and replay the clone. The downloaded audio data will shared between the resources, so you won’t download the audio file again, and the file will be automatically garbage collected once it finishes playing.