Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 audio - play sound repeatedly on click, regardless if previous iteration has finished

I'm building a game in which a wav file plays on click - in this case it's a gun sound "bang".

The problem is if I rapid click, it won't play the sound once for each click - it's as if the clicks are ignored while the sound is playing, and once the sound is finished, it starts listening for clicks again. The delay seems to be about one second long, so you figure if someone clicks 4 or 5 times per second, I want 5 bangs, not 1.

Here's my HTML:

<audio id="gun_sound" preload>
    <source src="http://www.seancannon.com/_test/audio/gun_bang.wav" />
</audio>

Here's my JS:

$('#' + CANVAS_ID).bind(_click, function() {
    document.getElementById('gun_sound').play();
    adj_game_data(GAME_DATA_AMMO_ID, -1);
    check_ammo();
}); 

Ideas?

like image 508
AlienWebguy Avatar asked Jul 31 '11 23:07

AlienWebguy


People also ask

How do you replay audio in HTML?

The loop attribute is a boolean attribute. When present, it specifies that the audio will start over again, every time it is finished.

Which attribute of audio tag identifies whether to replay the audio once it has stopped?

A Boolean attribute: if specified, the audio player will automatically seek back to the start upon reaching the end of the audio. A Boolean attribute that indicates whether the audio will be initially silenced. Its default value is false .

How check audio is playing or not in JavaScript?

The Audio tag has a paused property. If it is not paused, then it's playing.

How do you add sound effects in HTML?

HTML Audio - How It WorksThe controls attribute adds audio controls, like play, pause, and volume. The <source> element allows you to specify alternative audio files which the browser may choose from. The browser will use the first recognized format.


1 Answers

Once the gun_bang.wav is preloaded, you can dynamically make new elements with that sound attached to it, play the audio, and then remove them when the audio has finished.

function gun_bang() {
  var audio = document.createElement("audio");
  audio.src = "http://www.seancannon.com/_test/audio/gun_bang.wav";
  audio.addEventListener("ended", function() {
    document.removeChild(this);
  }, false);
  audio.play();
}

$('#' + CANVAS_ID).bind(_click, function() {
  gun_bang();
  adj_game_data(GAME_DATA_AMMO_ID, -1);
  check_ammo();
});
like image 133
Maverick Avatar answered Sep 21 '22 18:09

Maverick