有没有办法避免javascript /浏览器中的键盘延迟?

时间:2017-07-21 18:34:57

标签: javascript html browser keyboard latency

如果你弹钢琴,你会在演奏时感受到很大的延迟。我想避免延迟,因为它非常烦人。我果味循环,安装ASIO插件消除了延迟。这样的东西还是有一些黑魔法可以使它有效?

https://codepen.io/Schizomaru/pen/OjLyNX

$(function(){

    var $keyboard = $('.keyboard')
      , $buttons = $keyboard.find('button')
      , charMap = {}
      , keyList = []
      , char
      , audioCtx = new AudioContext()
      , oscMap = {};

    for(var i=0; i < $buttons.length; i++){
        char = $buttons[i].innerHTML;
        keyList.push(charMap[char] = {
            $button: $($buttons[i]),
            index:i,
            char:char,
            playing:false
        });
    }

    function getFreq(i){
        return 220 * Math.pow(2, (i+3)/12);
    }

    function playNote(obj, playing){
        if(obj && obj.playing != playing){
            obj.playing = playing;
            if(playing){
                if(!obj.osc){
                    obj.osc = audioCtx.createOscillator();
                    obj.osc.type = 'square';
                    obj.osc.frequency.value = getFreq(obj.index);
                    obj.osc.connect(audioCtx.destination);

                }
                obj.osc.start();
            } else {
                if(obj.osc){
                    obj.osc.stop();
                    obj.osc = null;
                }
            }
         obj.$button[playing ? 'addClass' : 'removeClass']('playing');
        }

    }

    $(window).on('keydown keyup', function(e){
        var c = e.originalEvent.key || '';
        playNote(charMap[c.toUpperCase()], e.type == 'keydown');
    });

    $keyboard.on('mousedown mouseup', 'button', function(e){
        var c = this.innerHTML;
        playNote(charMap[c.toUpperCase()], e.type == 'mousedown');
    })

})

0 个答案:

没有答案