如何在输入字段中无延迟地播放按键声音?

How to play a sound on key press in input field without delay?

我的 objective 是播放点击声音文件,类似于移动 phone 键盘的工作方式,但我在这里找到的每种方法似乎都会延迟声音文件重叠,即当我键入时在搜索字段中,声音有时会播放,具体取决于我键入的速度。

我正在使用以下代码:

$("#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();
});

CodePen

在音频文件的开头暂停和替换是诀窍。否则,如果事件发生在文件结束之前,则文件已经在播放...这给人一种 "skipped" 事件的印象。