Create a Live Coding Music App · Part 8 of 18 in the series
Part 8: A Synth for Bass and Lead
Build a mono synth for bass lines and leads: an oscillator, a low-pass filter and a gain that run the whole time, and notes that only move their settings. Note names become MIDI numbers, and two tags in the notation add accents and slides.
Create a Live Coding Music AppPart 8 of 18
On this page
Quest objectives
- Turn note names such as c2 and f#2 into MIDI note numbers
- Build a synth voice from an oscillator, a low-pass filter and a gain that never stop
- Move a setting toward a target with setTargetAtTime and its time constant
- Give every note a pluck with an envelope on the filter
- Add accents and slides with tags in the pattern
- Play drums and synth through the same kind of note event
The notation is complete since part 7, but all it plays is drums, and drums have no melody. This part builds a synth, an instrument that makes its sound from an oscillator, for bass lines and leads: the low notes under a track and the melody on top of it. The same notation plays it. Where a drum pattern says bd sd, a bass line says a1 c2.
Notes and their numbers
Part 1 turned MIDI note numbers into frequencies with midiToFreq(): a whole number per key of a piano, 69 for the A at 440 Hz. Nobody wants to write a bass line in numbers, so the patterns hold names. A name is one of the letters c, d, e, f, g, a and b, followed by the number of the octave. An octave is the distance from a note to the one with twice its frequency, and it is divided into twelve steps, the semitones. # after the letter raises the note by one semitone, b lowers it by one: f#2, eb3.
An instrument needs more than a pitch. It has to know when the note begins, how long it lasts and how hard it is played. All of that goes into one object, the NoteEvent, and everything that can play such events is an Instrument. Create src/notes.ts:
import type { Atom } from './mini.ts';
/** A note or a drum hit, at a time of the audio clock. */
export interface NoteEvent {
time: number;
/** How long the step is that the note fills, in seconds. */
duration: number;
/** The step as it was written, without tags: the name of a drum sound, or of a note. */
sound: string;
/** The MIDI note number, if the step is a note. */
note: number | undefined;
/** How hard the note is played, from 0 to 1. */
velocity: number;
accent: boolean;
slide: boolean;
}
/** Something that turns note events into sound. */
export interface Instrument {
play(event: NoteEvent): void;
/** Called when the music stops: let go of every note that is still held. */
stop(): void;
}A drum hit is a note event too: its sound is bd, and it has no note. The file goes on with the names:
const SEMITONES: Record<string, number> = { c: 0, d: 2, e: 4, f: 5, g: 7, a: 9, b: 11 };
/** The MIDI note number of a name such as c3, f#2 or eb4. C4 is 60. */
export function noteToMidi(name: string): number | undefined {
const match = /^([a-g])([#b]?)(\d)$/i.exec(name);
if (!match) return undefined;
const shift = match[2] === '#' ? 1 : match[2] === 'b' ? -1 : 0;
return 12 * (Number(match[3]) + 1) + SEMITONES[match[1].toLowerCase()] + shift;
}
/**
* Reads a step of a pattern: `c2` and `48` are notes, `bd` is a sound. After a colon come
* the tags: `c2:a` is played with an accent, `c2:s` slides into the next note, `c2:as` both.
*/
export function readAtom(atom: Atom): Pick<NoteEvent, 'sound' | 'note' | 'accent' | 'slide'> {
if (typeof atom === 'number') return { sound: String(atom), note: atom, accent: false, slide: false };
const [sound = '', tags = ''] = atom.split(':');
const number = Number(sound);
return {
sound,
note: Number.isFinite(number) ? number : noteToMidi(sound),
accent: tags.includes('a'),
slide: tags.includes('s'),
};
}noteToMidi() accepts one letter, an optional # or b, and one digit. c4 is 12 × 5 + 0 = 60, and a1 is 12 × 2 + 9 = 33, which midiToFreq() turns into 55 Hz. Anything else, such as bd, gives undefined: not a note.
readAtom() reads one step of a pattern. A number is taken as a MIDI note number. A word is split at the colon: before it stands the name, after it the tags, a for an accent and s for a slide. What they do to the sound comes below. The tokenizer needs no change, because it already counts # and : as letters of a word, so f#2:a arrives here as one step.
One voice that never stops
The drums of part 3 build new nodes for every hit and throw them away. That fits sounds that begin, fade and are gone. A bass line is different: it is one voice, and one note leads into the next. A synth with a single voice is called a mono synth. It plays one note at a time, and a new note takes over from the one before.
So this synth builds its nodes once, and they run for as long as the synth exists:
An oscillator produces the wave. The bass of this part uses a sawtooth, a wave that contains the frequency of the note and every whole multiple of it.
A low-pass filter lets the frequencies below its cutoff pass and turns down the ones above. It decides how many of the sawtooth's multiples are heard. Its resonance raises the frequencies right at the cutoff.
A gain node, the
gate, is closed between notes and opened for each note.A second gain node is the volume of the whole synth.
A note starts none of them. It moves their settings: the frequency of the oscillator, the cutoff of the filter, the gain of the gate.
Moving a setting toward a target
The ramps of part 1 lead from the value scheduled before to a new value at a fixed time. Here that is a problem. When a note begins, the gate can be anywhere: closed, open, or halfway through the fade of the note before. A ramp would need to know.
setTargetAtTime(target, startTime, timeConstant) doesn't. From startTime on, the value moves toward target from wherever it is at that moment, fast at first and then slower and slower. The time constant says how fast, in seconds: after one time constant the value has gone about 63 percent of the way to the target, after three about 95 percent, after five more than 99. It never arrives exactly, but the rest is soon too small to hear.
The gate opens with a time constant of 0.003. After 3 milliseconds it is 63 percent open, after 9 milliseconds 95 percent. That is fast enough to sound like an immediate start and slow enough not to click, which a jump in loudness would.
The synth
Create src/monoSynth.ts. It begins with the options:
import { audio, midiToFreq } from './audio.ts';
import type { Instrument, NoteEvent } from './notes.ts';
export type MonoSynthOptions = {
/** The shape of the oscillator's wave. */
wave: OscillatorType;
/** Where the filter rests, in hertz. Everything above it is turned down. */
cutoff: number;
/** How much the filter emphasizes the frequencies around its cutoff. */
resonance: number;
/** How far every note opens the filter, in octaves above the cutoff. */
envelope: number;
/** How long the filter takes to fall back, in seconds. */
decay: number;
volume: number;
};
/** The highest frequency the filter is opened to, in hertz. */
const CEILING = 16000;The options are written as a type and not as an interface. That makes no difference yet. Part 9 has a use for it. The class follows in the same file:
/**
* One voice for bass lines and leads: an oscillator, a low-pass filter that every note
* opens for a moment, and a gain that lets the note through. All three run the whole time.
* A note doesn't start them, it only moves their settings.
*/
export class MonoSynth implements Instrument {
private readonly context = audio();
private readonly oscillator = this.context.createOscillator();
private readonly filter = this.context.createBiquadFilter();
private readonly gate = this.context.createGain();
private readonly volume = this.context.createGain();
private options: MonoSynthOptions;
/** When the last note slides: the time at which it ends, and the next one takes over. */
private slideEnd: number | undefined;
constructor(output: AudioNode, options: MonoSynthOptions) {
this.options = options;
this.filter.type = 'lowpass';
this.gate.gain.value = 0;
this.oscillator.connect(this.filter).connect(this.gate).connect(this.volume).connect(output);
this.oscillator.start();
this.update(options);
}
update(options: MonoSynthOptions) {
this.options = options;
const now = this.context.currentTime;
this.oscillator.type = options.wave;
this.filter.Q.setTargetAtTime(options.resonance, now, 0.02);
this.filter.frequency.setTargetAtTime(options.cutoff, now, 0.02);
this.volume.gain.setTargetAtTime(options.volume, now, 0.02);
}
play(event: NoteEvent) {
if (event.note === undefined) return;
const { time } = event;
const hz = midiToFreq(event.note);
const end = time + event.duration;
if (this.slideEnd !== undefined && time <= this.slideEnd + 0.005) {
// The note before slides into this one: take back its release, and glide to the new pitch.
this.gate.gain.cancelScheduledValues(this.slideEnd - 0.001);
this.oscillator.frequency.setTargetAtTime(hz, time, 0.02);
} else {
this.oscillator.frequency.setValueAtTime(hz, time);
// An accent is louder, and opens the filter an octave further.
this.gate.gain.setTargetAtTime(event.velocity * (event.accent ? 1 : 0.6), time, 0.003);
const octaves = this.options.envelope + (event.accent ? 1 : 0);
const peak = Math.min(CEILING, this.options.cutoff * 2 ** octaves);
this.filter.frequency.setValueAtTime(peak, time);
this.filter.frequency.setTargetAtTime(this.options.cutoff, time, this.options.decay / 3);
}
this.gate.gain.setTargetAtTime(0, end, 0.015);
this.slideEnd = event.slide ? end : undefined;
}
stop() {
const now = this.context.currentTime;
this.gate.gain.cancelScheduledValues(now);
this.gate.gain.setTargetAtTime(0, now, 0.015);
this.slideEnd = undefined;
}
dispose() {
this.oscillator.stop();
this.volume.disconnect();
}
}The constructor plugs the four nodes into a row and starts the oscillator, with the gate closed. connect() gives back the node it connected to, so the row is a single chain of calls.
update() takes over a set of options. It moves the filter and the volume toward their new values with a time constant of 0.02, so that a change makes no click. dispose() stops the oscillator and unplugs the synth. Nothing calls these two from outside yet. The engine of the next two parts does.
A note and its pluck
The second branch of play() is the usual case, a note that starts fresh. Three things happen at its time:
The pitch jumps to the frequency of the note.
The gate opens, to 0.6 of the note's velocity.
The cutoff of the filter jumps up and falls back.
The third one shapes the sound. The course a value takes over a note is called an envelope. In part 1 it was the loudness, here it is the cutoff. envelope says how far up it jumps, in octaves. One octave up doubles a frequency, so with a cutoff of 300 Hz and an envelope of 3 the filter opens to 300 × 2 × 2 × 2 = 2400 Hz. CEILING keeps it at or below 16000 Hz.
From there the cutoff falls back with setTargetAtTime(). The time constant is a third of decay, so after decay seconds it has gone 95 percent of the way. What you hear: every note begins bright and gets dull within a fraction of a second, like a plucked string.
After either branch, the end of the note is scheduled. At end the gate closes with a time constant of 0.015. That fade is the release of the note.
Accent and slide
An accent sets one note apart from the others. a1:a opens the gate all the way instead of to 0.6, and opens the filter one octave further. The note is louder and brighter.
A slide ties a note to the next one. a2:s c2 plays the a2, and at the moment the c2 is due, the sound doesn't start over: the pitch bends down to the c2 and the tone goes on. For that, a note with a slide stores the time at which it ends in slideEnd. The next note compares its own time with it. If it begins there, it takes the first branch of play() and does two things:
It takes back the release of the note before it.
cancelScheduledValues(time)removes every change that is scheduled on a parameter at that time or later. The release was scheduled forslideEnd, so it is gone and the gate stays open.It glides to the new pitch, with
setTargetAtTime()and a time constant of 0.02: after 20 milliseconds the pitch has gone 63 percent of the way.
The filter is not opened again and the gate is left alone. A note that is slid into has no pluck of its own, and an accent on it changes nothing. It ends like any other note: its own release is scheduled at its own end.
Taking back the release works because of the clock of part 2. Notes are scheduled a moment before they are heard. When the next note is scheduled, the release of the note before it is on the schedule, but it hasn't begun.
The end of one note and the beginning of the next are worked out in two different ways, and floating point numbers can make them differ by a hair. So the comparison allows 5 milliseconds, and the cancelling starts 1 millisecond early.
stop() is for the Stop button: it removes whatever is scheduled on the gate and closes it.
The drums take the same events
The page should treat both instruments alike, so the drums become an Instrument too. In src/drums.ts, import the types Instrument and NoteEvent from ./notes.ts, and add implements Instrument to the first line of the class, between Drums and the brace. Then replace the head of play(). The cases stay as they are:
play(event: NoteEvent) {
const { time, velocity } = event;
switch (event.sound) {The drums keep hold of one sound only, the open hi-hat that is still ringing. Stopping cuts it off. Add stop() above choke():
stop() {
this.choke(this.context.currentTime);
}Two lines on the page
The page gets one input per instrument. In index.html, replace the <main> element:
<main class="stage">
<div class="line">
<label for="drums">drums</label>
<input id="drums" value="bd*4, ~ cp ~ cp, hh*8?0.2" spellcheck="false" autocomplete="off" />
<p class="message"></p>
</div>
<div class="line">
<label for="bass">bass</label>
<input id="bass" value="a1 a1:a [a2:s c2] <e2:s g2:as>" spellcheck="false" autocomplete="off" />
<p class="message"></p>
</div>
<p class="hint">Notes: c2, f#2, eb3 · c2:a is an accent, c2:s slides into the next note</p>
</main>The ids are gone from the messages. Each message is found as the element after its input. In src/style.css, change the gap of .stage from 16px to 8px, and add a rule for the labels above the rule for .line input:
.line label {
display: block;
margin-bottom: 4px;
color: var(--muted);
}In src/main.ts, the tempo slider and the position display at the end stay. Replace everything above them, from the imports to the handler of the Play button, with the next three blocks. The first one creates the instruments:
import { audio } from './audio.ts';
import { Clock } from './clock.ts';
import { Drums } from './drums.ts';
import { mini, MiniError, type Atom } from './mini.ts';
import { MonoSynth } from './monoSynth.ts';
import { readAtom, type Instrument } from './notes.ts';
import type { Pattern } from './pattern.ts';
import './style.css';
/** A line of the page: a pattern and the instrument that plays it. */
interface Line {
instrument: Instrument;
pattern: Pattern<Atom>;
}
const output = audio().destination;
const bass = new MonoSynth(output, {
wave: 'sawtooth',
cutoff: 300,
resonance: 8,
envelope: 3,
decay: 0.2,
volume: 0.5,
});
const lines: Line[] = [
line('#drums', new Drums(output)),
line('#bass', bass),
];The bass is a sawtooth with its filter at 300 Hz, which every note opens three octaves. line() is called here and written below. JavaScript allows that for functions declared with function. It follows next:
/** Connects an input of the page to an instrument. */
function line(selector: string, instrument: Instrument): Line {
const input = document.querySelector<HTMLInputElement>(selector)!;
const message = input.nextElementSibling!;
const result: Line = { instrument, pattern: mini(input.value) };
// Every key stroke is read. A pattern that can't be read leaves the last good one playing.
input.addEventListener('input', () => {
try {
result.pattern = mini(input.value);
message.textContent = '';
} catch (error) {
if (!(error instanceof MiniError)) throw error;
// Point at the place of the mistake, under the input's text.
message.textContent = `${' '.repeat(error.position)}^ ${error.message}`;
}
});
return result;
}That is the input handler of part 5, once per line. Each line keeps its own last good pattern and shows its own message. The clock asks all lines:
const clock = new Clock((from, to) => {
for (const { instrument, pattern } of lines) {
for (const hap of pattern(from, to)) {
instrument.play({
...readAtom(hap.value),
time: clock.timeAt(hap.begin),
duration: (hap.end - hap.begin) * clock.cycleSeconds,
velocity: 1,
});
}
}
});
const play = document.querySelector<HTMLButtonElement>('#play')!;
play.addEventListener('click', async () => {
await audio().resume();
if (clock.playing) {
clock.stop();
for (const { instrument } of lines) instrument.stop();
} else {
clock.start();
}
play.textContent = clock.playing ? '■ Stop' : '▶ Play';
play.classList.toggle('on', clock.playing);
});Every event of a pattern becomes a NoteEvent. readAtom() supplies the sound, the note and the tags. The clock supplies the time, and the length of the step in seconds: its length in cycles times the seconds of a cycle. When the music stops, every instrument is told.
Neither instrument complains about what it is sent. The synth ignores a step that is not a note, and the drums ignore a name they don't know. bd in the bass line is silent, and so is c2 in the drums.
Try it
Press Play. The bass plays a1 a1:a [a2:s c2] <e2:s g2:as> under the drums. A note that starts fresh begins bright and closes: the pluck. The second note has the accent and is louder and brighter than the first. In the third step the a2 bends down into the c2 without a new start. The last step is an e2 in one bar and an accented g2 in the next, and both slide down into the a1 that begins the following bar.
Remove the
:sfroma2:s. Thec2gets a pluck of its own.Type
c2:s g2:s c3:s g2. There is one pluck per bar, and the pitch bends from note to note.Type
a1*8, thena1:a*8: eight plain notes, then eight with an accent.The whole notation works on notes. Try
a1(3,8),a1 [c2 e2] a2 <g2 f#2>and{a1 c2 e2}%8, which runs three notes over eight steps.Type
a1 [c2into the bass. The message appears under that input, and the bass plays its last good pattern on while you fix it.
If you build along, change the options of the bass in src/main.ts. With envelope: 0 the pluck is gone, because the filter stays at its cutoff. Only the notes with an accent still open it, by their one octave. With decay: 0.6 the filter takes three times as long to close. wave: 'square' gives a different wave to filter.
Two inputs are as far as inputs go. Every new instrument would need another one, and its settings sit in the source code. In the next part the inputs make way for an editor, and the song becomes code.
Comments
The comments are GitHub Discussions: sign in with GitHub to write one.
The comments come from GitHub, through giscus. Loading them sends your IP address to giscus.app and GitHub.