Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 895
corazza Avatar asked Jan 04 '12 20:01

corazza


People also ask

Can multiple audio sources can be played in HTML?

By adding more "<audio>" tags you can add more audio players in the browser using HTML5...

What is the correct HTML5 element for playing audio files?

The HTML <audio> element is used to play an audio file on a web page.

What are the 2 tags for embedding audio in HTML?

To embed audio in HTML, we use the <audio> tag. Before HTML5, audio cannot be added to web pages in the Internet Explorer era. To play audio, we used web plugins like Flash. After the release of HTML5, it is possible.


2 Answers

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 } 
like image 197
DTrejo Avatar answered Oct 10 '22 11:10

DTrejo


I had this issue recently with an html5. Worked everywhere except safari. Using load() before calling play() solved this problem. It also helps to make sure that sound effects do not overlap with heavy clickers when event-handlers trigger sounds.

Here what I used <audio id="sound-one" preload="auto">     <source src="http://myurl/foo.mp3"></source>     <source src="http://myurl/foo.ogg"></source> </audio>   <a href="#" id="navigation-id">click here</a>      Jquery $("#navigation-id") //this attached is to an element on the page .mouseover(function() {     sound-one.load();                                    sound-one.play();     }); 
like image 33
Jay Avatar answered Oct 10 '22 09:10

Jay