ToneJS与键盘输入的性能滞后

时间:2018-04-19 22:00:44

标签: javascript web-audio

以下代码(https://codepen.io/anon/pen/JvoVxb)播放音高,但是,我发现它们是“慢”或“粘性”;如果你尝试和其他音乐一起演奏,你会发现它们有点滞后,很难让节奏正确。

直接使用WebAudio API时我没有发现这种情况(我发现QWERTY键盘性能几乎和数码钢琴一样好。)我想知道这是否是一个棘手的问题使用ToneJS(和为什么它正在发生?)......或者如果我在尝试使用它创建此功能时“做错了”。

    var keyToPitch = { " ":" ", "z":"C3", "s":"C#3", "x":"D3", "d":"D#3", "c":"E3", "v":"F3", "g":"F#3", "b":"G3", "h":"G#3", "n":"A3", "j":"A#3", "m":"B3", ",":"C4", "q":"C4", "2":"C#4", "w":"D4", "3":"D#4", "e":"E4", "r":"F4", "5":"F#4", "t":"G4", "6":"G#4", "y":"A4", "7":"A#4", "u":"B4", "i":"C5", "9":"C#5", "o":"D5", "0":"D#5", "p":"E5", "[":"F5", "=":"F#5", "]":"G5", "Backspace":"G#5", "\\":"A5" }

    var synth = new Tone.Synth()
    synth.oscillator.type = "sawtooth"
    synth.toMaster()

    window.addEventListener('keydown', this.onkeydown) 
    window.addEventListener('keyup', this.onkeyup) 

    // This is "slow", relative to WebAudio, it's not playing the pitch in a timely fashion...  
    function onkeydown(e){
        console.log(e.key)
        synth.triggerAttack(keyToPitch[e.key])      
    }
    function onkeyup(e){
        console.log(e.key)
        synth.triggerRelease()
    }

1 个答案:

答案 0 :(得分:1)

根据此处的Q& A:https://github.com/Tonejs/Tone.js/issues/306,可以通过传入currentTime来修复代码(而不是依赖于Tone的默认lookahead。)

function onkeydown(e){
    synth.triggerAttack(keyToPitch[e.key], Tone.context.currentTime)      
}