2017-08-16 69 views
-1

我的目标是播放一个类似于手机键盘工作方式的点击声音文件,但是我在这里找到的每种方法似乎都是从声音文件重叠延迟,即当我在搜索字段中输入时,声音有时会播放,具体取决于我输入的速度有多快。

我使用下面的代码:如何在按键输入字段中播放声音而不延迟?

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

但这种方法会导致有时点击,有时没有。

回答

2

如果你的嘟嘟声很短,如果你pause()currentTime重新定位为零...它似乎工作得很好。

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

CodePen

暂停和在音频文件的开头替换为的伎俩。否则,如果和事件发生在文件结束之前,文件已经在播放......这给人一种“跳过”事件的印象。