[英]How do you circumvent repeated keydown messages when you want to use them with javascript where you hold the key down but want it only to play once?
I have a piece of code that looks something like below and it works fine. 我有一段看起来像下面的代码,并且工作正常。 What it does is it launches an oscillator sound when the mouse clicks on a div named synth.It then stops playing the oscillator when the mouse button is released. 它的作用是在鼠标单击名为synth的div时发出振荡器声音,然后在释放鼠标按钮时停止播放振荡器。
synth.onmousedown= function () {
oscillator = context.createOscillator(), // Creates the oscillator
oscillator.type = synthWaveform.value;
oscillator.frequency.value = pitchInput.value;
oscillator.connect(context.destination); // Connects it to output
oscillator.noteOn(0);
};
synth.onmouseup = function () {
oscillator.disconnect();
};
I then added the code below so that when a user presses a keyboard charachter it triggers the oscillator. 然后,我在下面添加了代码,以便当用户按下键盘字符时触发振荡器。 The problem is that when the key is held down it repeadedly plays and then won't stop when the keyboard character is released. 问题在于,按住该键时,它会反复播放,然后在释放键盘字符时不会停止。 I want to know if there are any libraries or code that can be used to circumvent this. 我想知道是否有任何库或代码可用于规避此问题。 The goal is to have the end result be like a mousedown/up effect but with keyboard movements triggering the sound.Thank you. 我们的目标是使最终结果像鼠标按下/向上移动一样,但是键盘移动会触发声音。谢谢。
$('body').keydown(function() {
oscillator = context.createOscillator(), // Creates the oscillator
oscillator.type = synthWaveform.value;
oscillator.frequency.value = pitchInput.value;
oscillator.connect(context.destination); // Connects it to output
oscillator.noteOn(0);
});
$('body').keyup(function() {
oscillator.disconnect();
});
you could use underscore.js debounce if you need something fancier than the below option. 如果您需要比以下选项更高级的功能,则可以使用underscore.js反跳。
var keydown = false;
$('body').keydown(function() {
if(!keydown){
oscillator = context.createOscillator(), // Creates the oscillator
oscillator.type = synthWaveform.value;
oscillator.frequency.value = pitchInput.value;
oscillator.connect(context.destination); // Connects it to output
oscillator.noteOn(0);
keydown = true;
}
});
$('body').keyup(function() {
oscillator.disconnect();
keydown = false;
});
This might be a workaround 这可能是一种解决方法
var keyIsDown = false;
$('body').keydown(function() {
if(keyIsDown) {
// key is already down
return true;
}
keyIsDown = true;
// do your keydown handler
}
$('body').keyup(function() {
keyIsDown = false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.