Reputation: 1333
The follow code ( https://codepen.io/anon/pen/JvoVxb ) plays pitches, however, I've found them to be "slow" or "gummy"; if you try playing along with some other music, you will hear that they lag a bit and it is hard to get the rhythms right.
I've not found this to be the case when working directly with the WebAudio API (where I've found QWERTY-keyboard performance to be nearly as good as a digital piano.) I'm wondering if this an intractable problem with ToneJS (and why is it happening?) ... or if I am 'doing something wrong' in my attempts to create this functionality with it.
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()
}
Upvotes: 0
Views: 877
Reputation: 1333
Per the Q&A here: https://github.com/Tonejs/Tone.js/issues/306, the code can be fixed by passing in the currentTime
(as opposed to relying on Tone's default lookahead
.)
function onkeydown(e){
synth.triggerAttack(keyToPitch[e.key], Tone.context.currentTime)
}
Upvotes: 2