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?

我的梦境 提交于 2019-12-11 08:05:31

问题


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.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();

});

回答1:


you could use underscore.js debounce if you need something fancier than the below option.

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;
});



回答2:


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;
}


来源:https://stackoverflow.com/questions/14301728/how-do-you-circumvent-repeated-keydown-messages-when-you-want-to-use-them-with-j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!