Why can't I play sounds more than once using HTML5 audio tag?

corazza picture corazza · Jan 4, 2012 · Viewed 13.9k times · Source

This is how the sound is "stored":

<audio id = "hammer" src="res/sounds/Building/hammer.wav"></audio>

In the actual game (which I use sounds for), I use this to play the sound:

   function playSound(soundid)
   {
        document.getElementById(soundid).currentTime = 0;
        document.getElementById(soundid).play();
   }

But the sound plays only the first time, and never again! I tried resetting the "currentTime" in the console to 0, but I literally get this:

>document.getElementById("hammer").currentTime = 0
0
>document.getElementById("hammer").currentTime
0.340...

Why is this happening, how do I fix it?

Answer

DTrejo picture DTrejo · Jan 22, 2012

See this slide and the preceding three slides of Evan Wallace and Justin Ardini's presentation on html5 game dev.

For all the resources to make some awesome games, part of their talk: http://madebyevan.com/gamedevclass/

Audio still doesn't work consistently across all browsers, as of right now:

  • An element must be reloaded in Chrome or it will only play once
  • An element must not be reloaded in Firefox or there will be a delay
function playSoundEvent() {
  if (window.chrome) elems[index].load()
  elems[index].play()
  index = (index + 1) % elems.length
}