简体   繁体   English

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

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

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. 如果您的哔哔声很短,并且您将pause()并将currentTime重置为零,则它似乎工作得很好。

$("#search").on("keyup",function(){
  //console.log("ok");
  $("#beep")[0].pause();
  $("#beep")[0].currentTime=0;
  $("#beep")[0].play();
});

CodePen 密码笔

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. 否则,如果and事件在文件结束之前发生,则该文件已经在播放...这给人以“跳过”事件的印象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM