Skip to content

Create a Live Coding Music App · Part 9 of 18 in the series

Part 9: Code That Makes Music

The inputs make way for an editor. Its code describes a song through a small API that is built from a schema, running the code gives a patch of plain data, and an engine turns the patch into units that play. CodeMirror and two keys complete the page.

Quest objectives

  • Describe every type of unit in a schema and build the API of a song from it
  • Run the code of an editor with new Function and collect what it creates in a patch
  • Check a connection by what one unit gives and the other takes
  • Build an engine that creates the units of a patch and sends them their notes
  • Set up CodeMirror 6 with keys that run and stop the song

Two inputs were enough for a drum machine and a bass. They are not enough for a song. Every new instrument would need another input, and the settings of the synth sit in the source code, out of reach for anyone who only uses the page. This part is the turn of the series: the inputs go, an editor comes, and the song becomes code. From here on, whatever the app learns to do, the code in the editor can ask for.

It is also the biggest part. It has three new ideas, an API, a patch and an engine, and then an editor and a page to hold them.

A song is code

This is the song the editor is going to start with. Create src/song.ts:

src/song.ts
/** The code the editor starts with. */
export const SONG = `bpm(124)

const kit = drums()
pattern('bd*4, ~ cp ~ cp, hh*8?0.2').to(kit)
kit.to(out)

const bass = monoSynth({ cutoff: 300, resonance: 8 })
pattern('a1 a1:a [a2:s c2] <e2:s g2:as>').to(bass)
bass.to(out)
`;

The file is TypeScript, but the text between the backticks is the song, and the song is JavaScript that the app will run. It reads like this:

  • bpm(124) sets the tempo in beats per minute. That was the job of the slider.

  • drums() creates a drum machine and monoSynth() the synth of part 8. Its options set the filter: cutoff is the frequency the filter rests at, and resonance is how much it emphasizes that frequency.

  • pattern('…') creates a pattern from a text in mini-notation.

  • .to() connects. pattern('…').to(kit) sends the notes of the pattern to the drums, and kit.to(out) sends the sound of the drums to out, the speakers.

Three words go with this, in the code and for the rest of the series. Everything the code creates is a unit. A connection between two units is a cable, and it carries either notes or audio. The units, the cables and the tempo together are a patch, a word from synthesizers whose parts are connected by hand with cables.

The patch

The obvious way to build this is to let drums() create a drum machine on the spot. But the code is going to run again and again while the music plays, and each run would put new instruments on top of the ones that are playing. So running the code makes no sound at all. It only describes. A run gives a patch as plain data: a list of what should exist. Something else, the engine, makes that audible. Create src/patch.ts:

src/patch.ts
/** What an option of a unit can be set to. */
export type Value = number | string;
export type Options = Record<string, Value>;

/** One thing the code created: a pattern, an instrument, an effect. */
export interface UnitSpec {
  /** Its type and a count, such as monoSynth1: the same line of code gets the same id on every run. */
  id: string;
  type: string;
  options: Options;
}

/** A connection from one unit to another, by their ids. */
export interface Cable {
  from: string;
  to: string;
  kind: 'notes' | 'audio';
}

/** Everything a run of the code describes. Plain data: nothing in it makes a sound yet. */
export interface Patch {
  bpm: number;
  units: UnitSpec[];
  cables: Cable[];
}

A unit is written down as its type, its options and an id. The id is the type and a count, in the order in which the code creates the units. The starting song gives drums1, pattern1, monoSynth1 and pattern2. Its four cables carry notes from pattern1 to drums1 and from pattern2 to monoSynth1, and audio from drums1 and from monoSynth1 to out.

Plain data can be compared and passed around, and the next parts need both. Part 10 compares the patch of a run with what is playing and changes only the difference. Part 11 runs the code in a worker, which sends the finished patch to the page.

The API and its schema

bpm, drums, monoSynth, pattern and out are the API of a song: the names its code can use. The functions that create units are not written one by one. They are made from a description of every type of unit, the schema. Create src/schema.ts:

src/schema.ts
import type { Value } from './patch.ts';

export interface OptionSpec {
  doc: string;
  default: Value;
  /** The range of a number. */
  min?: number;
  max?: number;
  /** The words a text can be. */
  choices?: readonly string[];
}

export interface UnitType {
  doc: string;
  /** What its input takes, if it has one, and what its output gives. */
  takes?: 'notes' | 'audio';
  gives?: 'notes' | 'audio';
  options: Record<string, OptionSpec>;
}

A type of unit says what goes into it and what comes out of it, notes or audio, and lists its options, each with a default. The types follow in the same file:

src/schema.ts
const volume: OptionSpec = { doc: 'How loud it is, from 0 to 1.', default: 0.5, min: 0, max: 1 };

/** Every kind of unit the code can create: there is a function of the same name for each. */
export const UNITS: Record<string, UnitType> = {
  pattern: {
    doc: 'Plays notes written in mini-notation, one cycle per bar. Connect it to an instrument.',
    gives: 'notes',
    options: {
      source: { doc: 'The pattern, in mini-notation.', default: '' },
      velocity: { doc: 'How hard the notes are played, from 0 to 1.', default: 1, min: 0, max: 1 },
      legato: { doc: 'How much of its step a note is held: 0.5 is half of it.', default: 1, min: 0.05, max: 4 },
    },
  },
  drums: {
    doc: 'A drum machine. Sounds: bd sd hh oh cp rim lt mt ht cb cy.',
    takes: 'notes',
    gives: 'audio',
    options: { volume },
  },
  monoSynth: {
    doc: 'One voice for bass lines and leads. c2:a plays a note with an accent, c2:s slides into the next.',
    takes: 'notes',
    gives: 'audio',
    options: {
      wave: { doc: "The oscillator's wave.", default: 'sawtooth', choices: ['sawtooth', 'square', 'triangle', 'sine'] },
      cutoff: { doc: 'Where the filter rests, in hertz.', default: 300, min: 30, max: 8000 },
      resonance: { doc: 'How much the filter emphasizes its cutoff.', default: 8, min: 0.1, max: 20 },
      envelope: { doc: 'How far a note opens the filter, in octaves.', default: 3, min: 0, max: 6 },
      decay: { doc: 'How long the filter takes to close again, in seconds.', default: 0.2, min: 0.01, max: 2 },
      volume,
    },
  },
};

/** The speakers: `out` in the code. */
export const OUT: UnitType = { doc: 'The speakers.', takes: 'audio', options: {} };

A pattern gives notes. The drums and the mono synth take notes and give audio. out takes audio and gives nothing. That is all .to() has to know to tell a cable that makes sense from one that doesn't.

The defaults of monoSynth are the options the bass had in part 8. The doc texts, the ranges and the choices are not read by anything yet. Part 11 checks options against them, and part 17 shows them in the editor. From now on a new type of unit begins as an entry in this list, and the function for the song's code comes with it.

Running code into a patch

Create src/script.ts. It starts with what the song's code gets back from drums() or pattern(). That can't be the unit itself, because no drum machine exists while the code runs. It is a handle: an object that knows the id of a unit and can connect it.

src/script.ts
import { mini, MiniError } from './mini.ts';
import type { Options, Patch } from './patch.ts';
import { OUT, UNITS, type UnitType } from './schema.ts';

/** A mistake in the code that we found, as opposed to one JavaScript found. */
export class ScriptError extends Error {}

/** What the code holds in its variables: a unit of the patch, which can be connected. */
class Handle {
  readonly id: string;
  readonly type: string;
  private readonly spec: UnitType;
  private readonly patch: Patch;

  constructor(id: string, type: string, spec: UnitType, patch: Patch) {
    this.id = id;
    this.type = type;
    this.spec = spec;
    this.patch = patch;
  }

  /** Connects this unit to another one. Gives back the other one, so that calls can be chained. */
  to(target: Handle): Handle {
    if (!(target instanceof Handle)) throw new ScriptError(`${this.type}.to() needs something to connect to, such as out`);
    const gives = this.spec.gives;
    const takes = target.spec.takes;
    if (!gives) throw new ScriptError(`${this.type} has no output`);
    if (gives !== takes) {
      throw new ScriptError(`${this.type} gives ${gives}, but ${target.type} ${takes ? `takes ${takes}` : 'has no input'}`);
    }
    this.patch.cables.push({ from: this.id, to: target.id, kind: gives });
    return target;
  }
}

to() looks up in the schema what this unit gives and what the target takes. If the two match, it adds a cable to the patch. If they don't, it throws an error that says what is wrong: pattern('bd*4').to(out) ends in pattern gives notes, but out takes audio. And it gives back the target, so calls can be chained: pattern('bd*4').to(kit).to(out) connects the pattern to the kit and the kit to the speakers.

ScriptError marks the mistakes this code finds, as opposed to the ones JavaScript finds. Part 11 treats the two differently. The function that runs the code follows in the same file:

src/script.ts
/** Runs the code and gives back the patch it describes. */
export function runScript(code: string): Patch {
  const patch: Patch = { bpm: 120, units: [], cables: [] };
  const counts: Record<string, number> = {};

  /** Adds a unit to the patch: the options the code gave, on top of the defaults. */
  function create(type: string, given: Options = {}): Handle {
    const spec = UNITS[type];
    counts[type] = (counts[type] ?? 0) + 1;
    const options: Options = {};
    for (const [name, option] of Object.entries(spec.options)) options[name] = given[name] ?? option.default;
    const id = `${type}${counts[type]}`;
    patch.units.push({ id, type, options });
    return new Handle(id, type, spec, patch);
  }

  /** Everything the code can use, by name. */
  const api: Record<string, unknown> = {
    out: new Handle('out', 'out', OUT, patch),
    bpm(value: number) {
      patch.bpm = Math.min(240, Math.max(40, Number(value) || 120));
    },
  };
  for (const type of Object.keys(UNITS)) api[type] = (options?: Options) => create(type, options);

  // A pattern takes its text first. Reading it here finds mistakes before anything plays.
  api.pattern = (source: string, options?: Options) => {
    try {
      mini(String(source));
    } catch (error) {
      if (error instanceof MiniError) throw new ScriptError(`${error.message} at character ${error.position + 1} of "${source}"`);
      throw error;
    }
    return create('pattern', { ...options, source: String(source) });
  };

  // The code becomes the body of a function whose parameters are the names of the API.
  const run = new Function(...Object.keys(api), `"use strict";${code}`);
  run(...Object.values(api));
  return patch;
}

create() adds a unit to the patch. It goes through the options the schema lists and takes the value the code gave, or else the default. So a patch always holds every option of every unit. An option the schema doesn't list is dropped without a word: monoSynth({ cutof: 900 }) plays with the default cutoff. Part 11 turns that into a message.

api holds everything the song's code can use: out, bpm(), which keeps the tempo between 40 and 240, and one function per entry of the schema. pattern then gets a version of its own, because its text comes first and its options second. It also reads the text with mini() right away. A broken pattern stops the run with a message that names the character, before any of the new code is heard.

The last three lines run the code. new Function() makes a function out of text. Its last argument is the body, and the arguments before it are the names of the parameters. So the song becomes the body of a function with the parameters out, bpm, pattern, drums and monoSynth, and that function is called with the values of the API. Inside the song the names are there, without an import and without anything being put on window. The "use strict" in front makes JavaScript less forgiving: assigning to a name that was never declared is an error and not a new global variable.

When the function returns, the patch is complete, and not a single audio node has been created.

Units

On the other side of the patch is what makes the sound. For every unit of a patch the engine is going to create an object, and all of these objects have one shape. Create src/unit.ts:

src/unit.ts
import type { Clock } from './clock.ts';
import type { NoteEvent } from './notes.ts';
import type { Options } from './patch.ts';

/** A unit of the patch as it runs: what the engine creates for a UnitSpec. */
export interface Unit {
  /** Where audio comes in, and where it leaves. */
  readonly input?: AudioNode;
  readonly output?: AudioNode;
  /** Takes over new options without starting over. */
  update(options: Options): void;
  /** The notes this unit gives for a stretch of cycles. */
  events?(from: number, to: number, clock: Clock): NoteEvent[];
  /** Plays a note. */
  play?(event: NoteEvent): void;
  /** Called when the music stops: let go of every note that is still held. */
  stop?(): void;
  dispose(): void;
}

Most of it is optional, because units differ. A pattern has events(). An instrument has play() and an output. out has only an input. Every unit can take new options with update() and can be thrown away with dispose().

Unit takes the place of the Instrument of part 8. Remove the Instrument interface from src/notes.ts.

The unit behind pattern() is new. It does what the callback of the clock did in the src/main.ts of part 8: it asks a pattern for a stretch of cycles and turns the events into note events. Create src/player.ts:

src/player.ts
import type { Clock } from './clock.ts';
import { mini, type Atom } from './mini.ts';
import { readAtom, type NoteEvent } from './notes.ts';
import { silence, type Pattern } from './pattern.ts';
import type { Unit } from './unit.ts';

export type PlayerOptions = {
  source: string;
  velocity: number;
  legato: number;
};

/** Turns a pattern into note events: what `pattern('…')` in the code creates. */
export class Player implements Unit {
  private options: PlayerOptions;
  private pattern: Pattern<Atom> = silence();

  constructor(options: PlayerOptions) {
    this.options = options;
    this.update(options);
  }

  update(options: PlayerOptions) {
    this.options = options;
    this.pattern = mini(options.source);
  }

  events(from: number, to: number, clock: Clock): NoteEvent[] {
    return this.pattern(from, to).map((hap) => ({
      ...readAtom(hap.value),
      time: clock.timeAt(hap.begin),
      duration: (hap.end - hap.begin) * clock.cycleSeconds * this.options.legato,
      velocity: this.options.velocity,
    }));
  }

  dispose() {}
}

update() reads the text with mini(), so a player always holds a pattern that can be asked. Two options change the notes on their way. velocity is how hard they are played. legato scales their length: with 0.5 a note is held for half of its step. A slide needs the next note to begin where the one before it ends, so with a legato below 1 the slides of part 8 are gone. A player holds nothing that has to be released, so its dispose() is empty.

The two instruments change in the same way. Until now each of them was given a node to connect to and plugged itself in. As units they offer an output and leave the plugging to the engine, and they take their options as one object. In src/drums.ts, replace the imports:

src/drums.ts
import { audio } from './audio.ts';
import type { NoteEvent } from './notes.ts';
import type { Unit } from './unit.ts';

Replace the head of the class, from its comment down to the constructor, with the following. The options type above the class and update() are new:

src/drums.ts
export type DrumsOptions = {
  volume: number;
};

/** A drum machine without samples: every hit is built from oscillators and noise. */
export class Drums implements Unit {
  private readonly context = audio();
  /** Everything the kit plays goes through this gain: its volume. */
  readonly output = this.context.createGain();
  /** The open hi-hat that is still ringing. A closed one cuts it off. */
  private openHat: GainNode | undefined;

  constructor(options: DrumsOptions) {
    this.output.gain.value = options.volume;
  }

  update(options: DrumsOptions) {
    this.output.gain.setTargetAtTime(options.volume, this.context.currentTime, 0.02);
  }

The volume was fixed at 0.5 and is an option now. Add dispose() below stop():

src/drums.ts
dispose() {
  this.output.disconnect();
}

In src/monoSynth.ts, replace the imports as well:

src/monoSynth.ts
import { audio, midiToFreq } from './audio.ts';
import type { NoteEvent } from './notes.ts';
import type { Unit } from './unit.ts';

Replace the class from its first line down to the end of update(). The gain node volume is now called output and is public, the constructor takes only the options, and the chain of nodes ends at output:

src/monoSynth.ts
export class MonoSynth implements Unit {
  private readonly context = audio();
  private readonly oscillator = this.context.createOscillator();
  private readonly filter = this.context.createBiquadFilter();
  private readonly gate = this.context.createGain();
  readonly output = 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(options: MonoSynthOptions) {
    this.options = options;
    this.filter.type = 'lowpass';
    this.gate.gain.value = 0;
    this.oscillator.connect(this.filter).connect(this.gate).connect(this.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.output.gain.setTargetAtTime(options.volume, now, 0.02);
  }

play() and stop() stay as they are. Replace dispose():

src/monoSynth.ts
dispose() {
  this.oscillator.stop();
  this.output.disconnect();
}

The engine

The engine makes a patch audible. Create src/engine.ts. It begins with a table that says how a unit of each type is made:

src/engine.ts
import { audio } from './audio.ts';
import { Clock } from './clock.ts';
import { Drums, type DrumsOptions } from './drums.ts';
import { MonoSynth, type MonoSynthOptions } from './monoSynth.ts';
import type { Options, Patch } from './patch.ts';
import { Player, type PlayerOptions } from './player.ts';
import type { Unit } from './unit.ts';

/**
 * How a unit of each type is made. A patch holds its options as plain data. The script
 * filled in every option the schema lists, so here they are taken for what each unit expects.
 */
const FACTORIES: Record<string, (options: Options) => Unit> = {
  pattern: (options) => new Player(options as PlayerOptions),
  drums: (options) => new Drums(options as DrumsOptions),
  monoSynth: (options) => new MonoSynth(options as MonoSynthOptions),
};

A patch holds the options of a unit as a plain record of names and values, and each class wants its own options type. The script has filled in every option the schema lists, so the table takes the record for what the class expects, with as.

The class follows in the same file:

src/engine.ts
/** Makes a patch audible: creates its units, connects them, and sends them their notes. */
export class Engine {
  readonly clock = new Clock((from, to) => this.schedule(from, to));
  private readonly units = new Map<string, Unit>();
  /** For every unit that gives notes, the units that play them. */
  private routes = new Map<Unit, Unit[]>();

  constructor() {
    // `out` is a unit like the others: a gain in front of the speakers.
    const out = audio().createGain();
    out.connect(audio().destination);
    this.units.set('out', { input: out, update() {}, dispose() {} });
  }

  /** Replaces what is playing with a new patch. */
  apply(patch: Patch) {
    for (const [id, unit] of this.units) {
      if (id === 'out') continue;
      unit.dispose();
      this.units.delete(id);
    }
    for (const spec of patch.units) this.units.set(spec.id, FACTORIES[spec.type](spec.options));

    this.routes = new Map();
    for (const cable of patch.cables) {
      const from = this.units.get(cable.from)!;
      const to = this.units.get(cable.to)!;
      if (cable.kind === 'audio') from.output!.connect(to.input!);
      else this.routes.set(from, [...(this.routes.get(from) ?? []), to]);
    }
    this.clock.bpm = patch.bpm;
  }

  start() {
    this.clock.start();
  }

  stop() {
    this.clock.stop();
    for (const unit of this.units.values()) unit.stop?.();
  }

  /** Asks every unit that gives notes for the next stretch, and hands them to their players. */
  private schedule(from: number, to: number) {
    for (const [source, targets] of this.routes) {
      for (const event of source.events?.(from, to, this.clock) ?? []) {
        for (const target of targets) target.play?.(event);
      }
    }
  }
}

The engine owns the clock of part 2, which calls schedule() with every stretch of cycles that is about to be heard. out is a unit like the others and is made once: a gain node in front of the speakers, with nothing but an input.

apply() replaces what is playing with a new patch. It throws away every unit except out and creates the units of the patch from the table. Then it goes through the cables. An audio cable is a connection of the Web Audio API, from the output of one unit to the input of the other. A notes cable is nothing the Web Audio API knows. It becomes an entry in routes: for each unit that gives notes, the list of units that play them. The tempo comes last. The clock moves its anchor when the tempo is set, so the position in the song doesn't jump.

schedule() uses the routes. It asks each unit that gives notes for the events of the stretch and hands every event to every unit on its list. One pattern that is connected to two synths plays on both, and two patterns that are connected to one drum machine both play it.

What apply() does is crude, and it can be heard. Every run rebuilds all units. The old ones are unplugged in the middle of whatever they were sounding, and the notes that were already scheduled on them are lost. Each time you run the code while it plays, the sound is cut, even if you changed nothing. The position is kept: the clock runs on, and the new patterns are asked for the cycles the old ones would have been asked for. Part 10 removes the cut. There the engine keeps the units that are still in the patch and changes only what the code changed.

The editor

The editor is CodeMirror 6, a code editor for the browser that is put together from packages. Install five of them:

~/loopcode
$ npm install codemirror @codemirror/lang-javascript @codemirror/theme-one-dark @codemirror/state @codemirror/viewadded 19 packages, and audited 37 packages in 3s8 packages are looking for funding  run `npm fund` for detailsfound 0 vulnerabilities

codemirror brings the editor and a basic setup, @codemirror/lang-javascript knows JavaScript, and @codemirror/theme-one-dark is a dark color theme. @codemirror/state and @codemirror/view are the core of the editor, and the code imports from them directly. Create src/editor.ts:

src/editor.ts
import { javascript } from '@codemirror/lang-javascript';
import { Prec } from '@codemirror/state';
import { oneDark } from '@codemirror/theme-one-dark';
import { keymap } from '@codemirror/view';
import { basicSetup, EditorView } from 'codemirror';

export interface EditorKeys {
  /** Ctrl+Enter (Cmd+Enter on a Mac). */
  run(): void;
  /** Ctrl+. */
  stop(): void;
}

/** The page's colors for the editor's background. The theme after it fills in the rest. */
const look = EditorView.theme(
  {
    '&': { backgroundColor: 'var(--void)' },
    '.cm-gutters': { backgroundColor: 'var(--void)', border: 'none' },
    '.cm-activeLine, .cm-activeLineGutter': { backgroundColor: 'var(--night)' },
  },
  { dark: true },
);

/** A code editor in `parent`, holding `code`. */
export function createEditor(parent: HTMLElement, code: string, keys: EditorKeys): EditorView {
  return new EditorView({
    parent,
    doc: code,
    extensions: [
      // Before the basic setup, and with the highest precedence: Ctrl+Enter means
      // something else there.
      Prec.highest(
        keymap.of([
          { key: 'Mod-Enter', run: () => (keys.run(), true) },
          { key: 'Mod-.', run: () => (keys.stop(), true) },
        ]),
      ),
      basicSetup,
      javascript(),
      look,
      oneDark,
    ],
  });
}

A CodeMirror editor is an EditorView with a list of extensions, and everything it can do is an extension. basicSetup is a bundle of the usual ones, such as line numbers, undo and matching brackets. javascript() colors the code. oneDark is the theme, and look in front of it sets the backgrounds to the colors of the page. Where two extensions set the same thing, the earlier one wins, and oneDark fills in the rest.

The keys are an extension too. Mod stands for Ctrl, and for Cmd on a Mac. A handler gives back true to say that the key is dealt with. The basic setup has a binding of its own for Ctrl+Enter, which inserts a blank line, so the keymap is wrapped in Prec.highest() and comes before every other one. What the keys do is not the editor's business. The page passes that in as keys.

The page

Little is left of the page: the header, the editor and a status line. Replace index.html with:

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Loopcode</title>
  </head>
  <body>
    <header>
      <strong class="name">loopcode</strong>
      <button id="play">▶ Play</button>
      <span id="position" class="position">1.1</span>
      <span class="tempo"><span id="bpm">120</span> bpm</span>
      <button id="run" title="Ctrl+Enter">Run</button>
    </header>
    <main id="editor" class="editor"></main>
    <footer id="status" class="status"></footer>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>

The tempo slider is gone, because bpm() in the code sets the tempo. The header only shows the number, and it has a Run button. In src/style.css, replace everything from the .tempo rule to the end of the file with the following. That removes the rules of the slider and of .stage, .hint, .line and .message:

src/style.css
.tempo {
  margin-left: auto;
  color: var(--muted);
}

.editor {
  flex: 1;
  min-height: 0;
}

.editor .cm-editor {
  height: 100%;
}

.editor .cm-scroller {
  font: inherit;
  line-height: 1.5;
}

.status {
  min-height: 2.2em;
  padding: 6px 12px;
  background: var(--night);
  border-top: 2px solid var(--edge);
  color: var(--muted);
  white-space: pre-wrap;
}

.status.error {
  color: var(--orange);
}

The editor takes the room between the header and the status line. The page is a column of flex items, and a flex item is by default at least as tall as its content. min-height: 0 allows the editor to be smaller than its text, so a long song scrolls inside the editor. The status line turns orange for an error.

Replace src/main.ts with the next two blocks. The first holds the functions that run, start and stop:

src/main.ts
import { audio } from './audio.ts';
import { createEditor } from './editor.ts';
import { Engine } from './engine.ts';
import { runScript } from './script.ts';
import { SONG } from './song.ts';
import './style.css';

const engine = new Engine();

const play = document.querySelector<HTMLButtonElement>('#play')!;
const status = document.querySelector<HTMLElement>('#status')!;
const bpm = document.querySelector<HTMLSpanElement>('#bpm')!;

/** Runs the code in the editor. If it fails, what was playing plays on. */
function run(): boolean {
  try {
    const patch = runScript(editor.state.doc.toString());
    engine.apply(patch);
    bpm.textContent = String(patch.bpm);
    status.textContent = `${patch.units.length} units, ${patch.cables.length} cables`;
    status.classList.remove('error');
    return true;
  } catch (error) {
    status.textContent = String(error instanceof Error ? error.message : error);
    status.classList.add('error');
    return false;
  }
}

function start() {
  void audio().resume();
  if (!engine.clock.playing && run()) engine.start();
  showPlaying();
}

function stop() {
  engine.stop();
  showPlaying();
}

function showPlaying() {
  play.textContent = engine.clock.playing ? '■ Stop' : '▶ Play';
  play.classList.toggle('on', engine.clock.playing);
}

run() is the whole path in three lines. The text of the editor goes through runScript(), the patch goes to the engine, and the status line says what the patch holds. If the code throws, be it a syntax error, a name that doesn't exist or a ScriptError, the catch shows the message. engine.apply() was never reached, so what was playing plays on.

start() runs the code and starts the clock only if the run worked. It also resumes the audio context, which the browser allows after a click or a key, as in part 1. The rest of the file connects all this to the page:

src/main.ts
const editor = createEditor(document.querySelector<HTMLElement>('#editor')!, SONG, {
  // Ctrl+Enter starts the music, or runs the changed code while it plays.
  run: () => (engine.clock.playing ? run() : start()),
  stop,
});

play.addEventListener('click', () => (engine.clock.playing ? stop() : start()));
document.querySelector<HTMLButtonElement>('#run')!.addEventListener('click', () => {
  if (engine.clock.playing) run();
  else start();
});

/** Shows where the music is, as bar.beat, once per frame. */
const position = document.querySelector<HTMLSpanElement>('#position')!;
function draw() {
  const { clock } = engine;
  const cycle = clock.playing ? Math.max(0, clock.cycleAt(audio().currentTime)) : 0;
  position.textContent = `${Math.floor(cycle) + 1}.${Math.floor((cycle % 1) * 4) + 1}`;
  requestAnimationFrame(draw);
}
draw();

Ctrl+Enter in the editor starts the music, or runs the changed code while it plays. Ctrl+. stops it. On a Mac both take Cmd in place of Ctrl. The Play button starts and stops, and the Run button does what Ctrl+Enter does. draw() is the display of part 2, with the clock taken from the engine.

Try it

Press Play, or click into the editor and press Ctrl+Enter. The song plays, and the status line reads 4 units, 4 cables.

  • Change bpm(124) to bpm(90) and press Ctrl+Enter. The song is slower, the header shows 90, and at the moment of the run you hear the cut.

  • Give the bass other options: monoSynth({ cutoff: 800, resonance: 12, decay: 0.5 }). The notes are brighter, and the filter takes longer to close.

  • Delete the line kit.to(out) and run. The drums are silent, and the status line counts one cable fewer. That is no mistake to the app: a unit that nothing listens to is allowed. Put the line back.

  • Add pattern('~ ~ ~ [~ rim]').to(kit) below the first pattern. Two patterns play the same kit, and the status line reads 5 units, 5 cables.

  • Write pattern('bd*4').to(out) at the end. The status line turns orange and reads pattern gives notes, but out takes audio, and the music plays on as it was.

  • Make two more mistakes. drum() in place of drums() gives drum is not defined in Chrome. pattern('bd [sd') gives Missing "]" at character 7 of "bd [sd". The messages say what is wrong, but not in which line. Part 11 adds that.

The song is JavaScript, so everything JavaScript has is there: variables, loops, functions. Replace the whole song with this one and run it:

javascript
bpm(110)

const kit = drums({ volume: 0.4 })
for (const beat of ['bd(3,8)', '~ sd', 'hh*<4 8>']) {
  pattern(beat).to(kit)
}
kit.to(out)

const lead = monoSynth({ wave: 'square', cutoff: 800, envelope: 2, decay: 0.1 })
pattern('{c3 e3 g3 a3 c4}%8', { legato: 0.5 }).to(lead).to(out)

The loop creates three patterns for one kit, and the last line plugs two cables in one go. The status line reads 6 units, 6 cables. The lead runs five notes over eight steps, so its figure begins on a different step in every bar, and with legato: 0.5 each note stops halfway through its step.

One thing stands between this and live coding: the cut at every run. The next part takes it away.

The app at the end of part 9. Press Play, change the code and press Ctrl+Enter (Cmd+Enter on a Mac) to run it. Ctrl+. stops. The line under the editor shows what the run created, or what went wrong.
Open in a new tab

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.