My objective is to play a clicking sound file similar to how mobile phone keypads work , but every method I find on here seems to delay from the sound file overlapping, ie When I type in the search field the sound will sometimes play depending on how fast I type.
I am using the following code:
$("#search") // loop each menu item
.each(function(i) {
if (i != 0) { // only clone if more than one needed
$("#beep")
.clone()
.attr("id", "beep-" + i)
.appendTo($(this).parent());
}
$(this).data("beeper", i); // save reference
})
.keydown(function() {
$("#beep-" + $(this).data("beeper"))[0].play();
});
$("#beep").attr("id", "beep-0"); // get first one into naming convention
But this method results in sometimes clicking , sometimes not.
If your beep sound is short and if you pause()
and reposition the currentTime
to zero... It seems to work quite fine.
$("#search").on("keyup",function(){
//console.log("ok");
$("#beep")[0].pause();
$("#beep")[0].currentTime=0;
$("#beep")[0].play();
});
Pausing and replacing at the beginning of the audio file is the trick. Else, if and event occurs before the file has ended, the file is already playing... Which gives the impression of a "skipped" event.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.