Reputation: 35
I'm trying to play audio when pressing keys on the keyboard. For some reason, I cannot replay one and the same sound until the audio file has finished playing.
Here's my html setup:
<audio id="65" src="assets/sounds/tom.wav"></audio>
<audio id="83" src="assets/sounds/tink.wav"></audio>
<audio id="68" src="assets/sounds/kick.wav"></audio>
...
and the jQuery
$(document).keydown(function(e) {
var code = e.which;
$("#"+code).get(0).play();
});
So, if tom.wav is 4sec long, I can hammer "A" on the keyboard as many times as I want to. It won't play again before those 4sec have passed.
Any ideas?
Upvotes: 1
Views: 193
Reputation: 337560
To restart an audio file you need to first pause it, then set it's currentTime
to 0
, before making it play again. Try this:
$(document).keydown(function(e) {
var audio = $('#' + e.which)[0];
audio.pause();
audio.currentTime = 0;
audio.play();
});
Upvotes: 1