ToneJS:多音高键盘输入
ToneJS: Multi-pitch keyboard entry
This pen 使用 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" }
var synth = new Tone.Synth()
synth.oscillator.type = "sawtooth"
synth.toMaster()
window.addEventListener('keydown', this.onkeydown)
window.addEventListener('keyup', this.onkeyup)
function onkeydown(e){
synth.triggerAttack(keyToPitch[e.key], Tone.context.currentTime)
}
function onkeyup(e){
synth.triggerRelease()
}
ToneJS 中的振荡器是音频源,Master 是播放与其连接的所有输入的输出。因此,要播放多个重叠的声音,您只需创建多个振荡器并将它们全部连接到 Master。
对于您链接到的那种演示,典型的做法可能是制作固定数量(比如 5 个)的振荡器,并在您想要触发声音时轮流通过它们:
var synthIndex = 0
function startSound(){
synthIndex = (synthIndex + 1) % voices
var synth = synths[synthIndex]
synth.triggerAttack(/* ... */)
}
或类似。原则上,您可以为每个音调制作一个单独的振荡器,但这可能会影响不那么琐碎的演示中的性能。
This pen 使用 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" }
var synth = new Tone.Synth()
synth.oscillator.type = "sawtooth"
synth.toMaster()
window.addEventListener('keydown', this.onkeydown)
window.addEventListener('keyup', this.onkeyup)
function onkeydown(e){
synth.triggerAttack(keyToPitch[e.key], Tone.context.currentTime)
}
function onkeyup(e){
synth.triggerRelease()
}
ToneJS 中的振荡器是音频源,Master 是播放与其连接的所有输入的输出。因此,要播放多个重叠的声音,您只需创建多个振荡器并将它们全部连接到 Master。
对于您链接到的那种演示,典型的做法可能是制作固定数量(比如 5 个)的振荡器,并在您想要触发声音时轮流通过它们:
var synthIndex = 0
function startSound(){
synthIndex = (synthIndex + 1) % voices
var synth = synths[synthIndex]
synth.triggerAttack(/* ... */)
}
或类似。原则上,您可以为每个音调制作一个单独的振荡器,但这可能会影响不那么琐碎的演示中的性能。