Controllers
Once we've set up our oscillators, LFOs, filters, and envelopes, we'll need a
way to control them. In Max, you can use the ctlin or midiin objects
to hook into an external device like a MIDI keyboard or drum pad. There
actually exists a way to do this in JavaScript as well, by using the Web MIDI
API. Unfortunately, at the time of this recording in March 2019, the Web MIDI
API is not widely implemented among browsers, only usable in Google Chrome.
So, instead of MIDI, let's use the computer keyboard to control notes. You can
use the events "keyup"
and
"keydown"
to track the keyboard movements.
Here's how to track these motions with jQuery.
$(document).keydown((event) => {
let asciiValue = event.which;
});
An "ASCII value" is an integer value from 0 to 127 that is associated with a
particular key on a computer keyboard. For instance, the ASCII value of "c" is
67. Let's play middle C, aka C4, whenever the "c" key is pressed. The
frequency of middle C is 261.63 Hz.
const audioCtx = new AudioContext();
const playMiddleC = () => {
const oscillator = audioCtx.createOscillator();
oscillator.frequency.value = 261.63;
const oscillatorGain = audioCtx.createGain();
oscillator.connect(oscillatorGain);
oscillatorGain.connect(audioCtx.destination);
oscillator.start();
oscillatorGain.gain.setValueAtTime(0, audioCtx.currentTime);
oscillatorGain.gain.linearRampToValueAtTime(1, audioCtx.currentTime + 0.1);
oscillatorGain.gain.linearRampToValueAtTime(0, audioCtx.currentTime + 1);
oscillator.stop(audioCtx.currentTime + 1); // remember to stop the oscillator in order
// to trigger the garbage collector
};
$(document).keyup((event) => {
if (event.which === 67) {
playMiddleC();
}
});
You can download this code in the page below this video. Try expanding it such
that you can play different notes with different strokes on your computer
keyboard!