[英]How to play a sound on key press in input field without delay?
我的目標是播放類似於手機鍵盤工作原理的點擊聲音文件,但是我在此處找到的每種方法似乎都因聲音文件重疊而延遲,例如,當我在搜索字段中鍵入內容時,聲音有時會根據播放速度而有所不同我鍵入。
我正在使用以下代碼:
$("#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
但是這種方法有時會單擊,有時不會。
如果您的嗶嗶聲很短,並且您將pause()
並將currentTime
重置為零,則它似乎工作得很好。
$("#search").on("keyup",function(){
//console.log("ok");
$("#beep")[0].pause();
$("#beep")[0].currentTime=0;
$("#beep")[0].play();
});
暫停和替換音頻文件的開頭是竅門。 否則,如果and事件在文件結束之前發生,則該文件已經在播放...這給人以“跳過”事件的印象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.