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 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.

//Sample sound table
var sounds = {"smallexpl":new Audio("Sounds/Explosion.ogg"), "longexpl":new Audio("Sounds/LongExplosion.ogg")};

//Resets a sound's timer and plays it from the start
function playSound(name){
sounds[name].currentTime = 0;

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

This entry was posted in html5, javascript and tagged , , . Bookmark the permalink.

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

  1. Kerriann says:

    That’s a mold-breaker. Great tkhniing!

  2. Gibbs says:

    Current time! I should of known.

    Thanks for that.

  3. Chris Pearce says:

    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.


  4. Mukesh Mehra says:

    currentTime seems to be giving problem in iOS, In my testing It worked fine all over else iPad.

Leave a Reply

Your email address will not be published. Required fields are marked *