Skip to content

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

Part 3: Drums From Oscillators and Noise

Build a drum machine without a single recording: a kick from a sine with a falling pitch, a snare and a clap from filtered noise, hi-hats from six square waves, and an open hi-hat that a closed one cuts off. Then play a beat written as sixteen steps of x and dots.

Quest objectives

  • Make white noise in a buffer and play it
  • Build a kick, a snare, a clap and hi-hats from oscillators and noise
  • Shape a sound with a high-pass and a band-pass filter
  • Let a closed hi-hat cut off an open one
  • Write a beat as sixteen steps and play it with the clock

The clock of part 2 plays a metronome. Now it gets a drum machine: an instrument that plays drum sounds by itself, step by step. Most drum machines play samples, short recordings of drums. This one has no recordings. Every hit is built at the moment it plays, out of the two kinds of source the Web Audio API has for it: oscillators and noise. Early drum machines worked the same way, with circuits where this one has code.

It is the better way to learn, too. Every sound is a handful of numbers that you can change, and what it takes, envelopes, falling pitches and filters, is what the synths of the later parts are made of.

Noise

An oscillator repeats one wave, so it has a pitch. Noise is the opposite: a wave of random numbers in which nothing repeats. It has no pitch, because all frequencies are in it at once, and it is heard as a hiss. Everything in a drum kit that rattles or rustles starts as noise.

The Web Audio API has no node that makes noise, but it plays any numbers it is given. An AudioBuffer holds sound as a list of numbers between -1 and 1, as many per second as the context's sampleRate says, and an AudioBufferSourceNode plays such a buffer. Create src/drums.ts. It begins with the names of the kit's sounds, six frequencies that the hi-hats need further down, and the noise:

src/drums.ts
import { audio } from './audio.ts';

/** The sounds of the kit, by the short names drum patterns are written with. */
export const DRUM_SOUNDS = ['bd', 'sd', 'hh', 'oh', 'cp', 'rim', 'lt', 'mt', 'ht', 'cb', 'cy'] as const;
export type DrumSound = (typeof DRUM_SOUNDS)[number];

/** The six square waves of a TR-808 hi-hat. Their odd ratios make the metallic sound. */
const METAL = [205.3, 304.4, 369.6, 522.7, 540, 800];

let noiseBuffer: AudioBuffer | undefined;

/** Two seconds of white noise, made once: random numbers between -1 and 1. */
function noise(context: AudioContext): AudioBufferSourceNode {
  if (!noiseBuffer) {
    noiseBuffer = context.createBuffer(1, context.sampleRate * 2, context.sampleRate);
    const data = noiseBuffer.getChannelData(0);
    for (let i = 0; i < data.length; i += 1) data[i] = Math.random() * 2 - 1;
  }
  const source = context.createBufferSource();
  source.buffer = noiseBuffer;
  source.loop = true;
  return source;
}

The buffer is filled once, with two seconds of random numbers, and all hits share it. The source node is new for every hit: like an oscillator, it can be started only once. It loops, so it can't run out, however long a hit lasts.

The names are the usual short ones for drum sounds: bd is the bass drum, also called the kick, sd the snare drum, hh the closed hi-hat, oh the open hi-hat, cp the clap, rim the rim shot, a stick on the edge of a drum, lt, mt and ht the low, the mid and the high tom, cb the cowbell and cy the cymbal. The rhythms of the following parts are written with these names.

One envelope for every hit

A drum is struck and dies away. Its envelope is the one of part 1 with a faster start: up to the peak within a millisecond, then an exponential fall. Most sounds of the kit use it. The next block follows in the same file:

src/drums.ts
/** A hit's loudness: up to `peak` in a millisecond, then falling away over `decay` seconds. */
function hit(gain: AudioParam, time: number, peak: number, decay: number): number {
  gain.setValueAtTime(0, time);
  gain.linearRampToValueAtTime(peak, time + 0.001);
  gain.exponentialRampToValueAtTime(peak * 0.001, time + 0.001 + decay);
  return time + decay + 0.01;
}

The function gets the gain parameter of a gain node and plans the three steps on it. The fall ends at a thousandth of the peak. What it returns is the moment at which the hit is over, a few milliseconds after the end of the fall: the caller stops its oscillators or its noise then.

Two filters

A filter turns down a part of the frequencies in a sound and lets the rest through. The kit uses two kinds. A high-pass lets through what lies above its frequency and turns down what lies below. A band-pass lets through a band around its frequency and turns down what lies below and above; its Q says how narrow the band is, and a higher Q is a narrower band. Both are a BiquadFilterNode with a different type. A filter is what makes different sounds out of the same hiss: it decides which part of the noise is left.

The recipes

  • Kick and toms, in drum(): one sine oscillator with a falling pitch. The kick begins at 288 Hz, six times the 48 Hz it ends on, and is down there within 40 ms. The fall is the knock of the beater, and the low sine that is left is the body of the drum, which fades over 0.45 seconds. The toms are the same recipe at 82, 110 and 148 Hz with a smaller and slower fall: from 2.5 times the pitch, in 60 ms.

  • Snare, in snare(): two layers. Noise through a high-pass at 1800 Hz is the rattle of the wires that are stretched under a snare drum. A sine that falls from 370 Hz to 185 Hz in 20 ms is the drum's skin. The noise lasts longer than the sine: 0.18 seconds against 0.1.

  • Clap, in clap(): several hands never clap at the same instant. Noise through a band-pass at 1300 Hz gets three short bursts, 11 ms apart, each falling from 80 to 4 percent of the peak within 9 ms. A fourth one at 33 ms starts at the full peak and takes 120 ms to fade: the tail.

  • Hi-hats and cymbal, in metal(): a sheet of metal does not ring at one pitch. Six square waves at 205.3, 304.4, 369.6, 522.7, 540 and 800 Hz sound together. These frequencies stand in no simple ratio to one another, so the six don't blend into one note. With all their overtones they make a dense cluster, and a band-pass at 9800 Hz and a high-pass at 7000 Hz leave only its top. The closed hi-hat fades in 0.05 seconds, the open one in 0.35. The cymbal has lower filters, at 5000 and 3500 Hz, and takes 1.4 seconds.

  • Rim shot and cowbell, in tone(): square waves through a band-pass. The rim shot is one wave at 1700 Hz that is over after 25 ms. The cowbell is two, at 540 and 800 Hz, that fade for a quarter of a second.

The class is the rest of the file:

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

  constructor(output: AudioNode) {
    this.output.gain.value = 0.5;
    this.output.connect(output);
  }

  play(sound: string, time: number, velocity = 1) {
    switch (sound) {
      case 'bd':
        return this.drum(time, velocity, 48, 6, 0.04, 0.45);
      case 'sd':
        return this.snare(time, velocity);
      case 'cp':
        return this.clap(time, velocity);
      case 'hh':
        this.choke(time);
        return void this.metal(time, velocity * 0.5, 0.05, 9800, 7000);
      case 'oh':
        this.choke(time);
        this.openHat = this.metal(time, velocity * 0.35, 0.35, 9800, 7000);
        return;
      case 'cy':
        return void this.metal(time, velocity * 0.25, 1.4, 5000, 3500);
      case 'lt':
        return this.drum(time, velocity, 82, 2.5, 0.06, 0.35);
      case 'mt':
        return this.drum(time, velocity, 110, 2.5, 0.06, 0.35);
      case 'ht':
        return this.drum(time, velocity, 148, 2.5, 0.06, 0.35);
      case 'rim':
        return this.tone(time, velocity * 0.5, [1700], 0.025, 1700, 3);
      case 'cb':
        return this.tone(time, velocity * 0.2, [540, 800], 0.25, 800, 1.5);
    }
  }

  /** Kick and toms: a sine whose pitch falls from `hz * punch` to `hz`. */
  private drum(time: number, peak: number, hz: number, punch: number, fall: number, decay: number) {
    const oscillator = this.context.createOscillator();
    oscillator.frequency.setValueAtTime(hz * punch, time);
    oscillator.frequency.exponentialRampToValueAtTime(hz, time + fall);
    const envelope = this.context.createGain();
    oscillator.connect(envelope).connect(this.output);
    oscillator.start(time);
    oscillator.stop(hit(envelope.gain, time, peak, decay));
  }

  /** Snare: noise above 1800 Hz for the wires, and a short sine for the drum's skin. */
  private snare(time: number, peak: number) {
    const wires = noise(this.context);
    const highpass = this.context.createBiquadFilter();
    highpass.type = 'highpass';
    highpass.frequency.value = 1800;
    const wiresEnvelope = this.context.createGain();
    wires.connect(highpass).connect(wiresEnvelope).connect(this.output);
    wires.start(time, Math.random());
    wires.stop(hit(wiresEnvelope.gain, time, peak * 0.6, 0.18));

    const skin = this.context.createOscillator();
    skin.frequency.setValueAtTime(370, time);
    skin.frequency.exponentialRampToValueAtTime(185, time + 0.02);
    const skinEnvelope = this.context.createGain();
    skin.connect(skinEnvelope).connect(this.output);
    skin.start(time);
    skin.stop(hit(skinEnvelope.gain, time, peak * 0.5, 0.1));
  }

  /** Clap: three short bursts of noise, a few milliseconds apart, and a tail. */
  private clap(time: number, peak: number) {
    const source = noise(this.context);
    const bandpass = this.context.createBiquadFilter();
    bandpass.type = 'bandpass';
    bandpass.frequency.value = 1300;
    bandpass.Q.value = 1.2;
    const envelope = this.context.createGain();
    source.connect(bandpass).connect(envelope).connect(this.output);

    const gain = envelope.gain;
    gain.setValueAtTime(0, time);
    for (const offset of [0, 0.011, 0.022]) {
      gain.setValueAtTime(peak * 0.8, time + offset);
      gain.exponentialRampToValueAtTime(peak * 0.04, time + offset + 0.009);
    }
    gain.setValueAtTime(peak, time + 0.033);
    gain.exponentialRampToValueAtTime(peak * 0.001, time + 0.153);
    source.start(time, Math.random());
    source.stop(time + 0.16);
  }

  /** Hi-hats and cymbal: six square waves through a band-pass and a high-pass. */
  private metal(time: number, peak: number, decay: number, band: number, floor: number): GainNode {
    const mix = this.context.createGain();
    const bandpass = this.context.createBiquadFilter();
    bandpass.type = 'bandpass';
    bandpass.frequency.value = band;
    bandpass.Q.value = 0.8;
    const highpass = this.context.createBiquadFilter();
    highpass.type = 'highpass';
    highpass.frequency.value = floor;
    const envelope = this.context.createGain();
    // A gain of its own after the envelope, so that the hit can be cut off later.
    const out = this.context.createGain();
    mix.connect(bandpass).connect(highpass).connect(envelope).connect(out).connect(this.output);

    const end = hit(envelope.gain, time, peak, decay);
    for (const hz of METAL) {
      const oscillator = this.context.createOscillator();
      oscillator.type = 'square';
      oscillator.frequency.value = hz;
      oscillator.connect(mix);
      oscillator.start(time);
      oscillator.stop(end);
    }
    return out;
  }

  /** Rim shot and cowbell: short square waves through a band-pass. */
  private tone(time: number, peak: number, pitches: number[], decay: number, band: number, q: number) {
    const bandpass = this.context.createBiquadFilter();
    bandpass.type = 'bandpass';
    bandpass.frequency.value = band;
    bandpass.Q.value = q;
    const envelope = this.context.createGain();
    bandpass.connect(envelope).connect(this.output);

    const end = hit(envelope.gain, time, peak, decay);
    for (const hz of pitches) {
      const oscillator = this.context.createOscillator();
      oscillator.type = 'square';
      oscillator.frequency.value = hz;
      oscillator.connect(bandpass);
      oscillator.start(time);
      oscillator.stop(end);
    }
  }

  /** A closed hi-hat stops the open one, as on a real pair of cymbals. */
  private choke(time: number) {
    if (!this.openHat) return;
    this.openHat.gain.setTargetAtTime(0, time, 0.004);
    this.openHat = undefined;
  }
}
  • Everything goes through one gain node, output, set to 0.5: the volume of the kit. The constructor connects it to the node it is given.

  • play() picks the recipe by the sound's name and ignores names it does not know. velocity is how hard the drum is hit, with 1 for a full hit, and scales the peak of the envelope. The factors next to it, such as 0.5 for the closed hi-hat and 0.2 for the cowbell, balance the sounds against one another.

  • An oscillator whose type is not set is a sine. drum() and the skin of the snare rely on that.

  • frequency is an audio parameter like gain, so a pitch can be ramped in the same way. The falling pitch of the kick is one exponentialRampToValueAtTime().

  • The noise starts at a random place: start(time, Math.random()) begins up to a second into the buffer. No two snare hits are the same piece of noise.

  • clap() plans its envelope by hand, without hit(): setValueAtTime() jumps up, the ramp falls, three times over, and then comes the tail.

  • In metal(), the six oscillators run into mix, a gain node that does nothing but collect them. The method returns a node, which play() only needs for the open hi-hat. return void this.metal(…) throws it away for the others.

The open hi-hat

A hi-hat is a pair of cymbals on a stand with a pedal. Open, they ring. Closed, they make a short tick, and closing them ends the ringing. A drum machine copies that: a closed hi-hat cuts off an open one that still sounds. Without it, the open hi-hat would ring on across the closed ones after it, and the two would no longer be heard as one instrument.

For that, something has to get hold of a sound that is playing already. The envelope's gain is no good for it: its values are planned to the end of the hit, and a cut would have to break into that plan. So metal() puts one more gain node behind the envelope, out, on which nothing is planned. play() keeps the one of the last open hi-hat in openHat, and choke() turns it down: setTargetAtTime(0, time, 0.004) lets the gain approach 0 from time on and cover about two thirds of what is left every 4 ms. After 20 ms less than a hundredth of the sound is left, and because the gain never jumps, the cut makes no click. The open hi-hat calls choke() first as well, so it also ends the open one before it.

A beat in sixteen steps

A drum machine divides the bar into sixteen steps, four to a beat, and every sound is on or off at every step. Written down, that is a string of sixteen characters per sound: an x plays, a dot is silent.

In index.html, replace the <main> element. The stage gets a place for a row of pads, and the hint changes:

index.html
<main class="stage">
  <div id="pads" class="pads"></div>
  <p class="hint">Click a pad to hear a sound, or press Play for the beat.</p>
</main>

In src/main.ts, beep() and the metronome go, and with them the import of midiToFreq. The function itself stays in src/audio.ts: the synth of part 8 needs it. Replace everything above the Play button, from the imports down to the metronome, with:

src/main.ts
import { audio } from './audio.ts';
import { Clock } from './clock.ts';
import { DRUM_SOUNDS, Drums } from './drums.ts';
import './style.css';

const drums = new Drums(audio().destination);

/** One bar in sixteen steps per sound: x plays, a dot is silent. */
const BEAT: Record<string, string> = {
  bd: 'x...x...x...x...',
  sd: '....x.......x...',
  hh: 'x.x.x.x.x.xxx.x.',
  oh: '..............x.',
};

const clock = new Clock((from, to) => {
  // Steps are sixteenths of a cycle. Take every step that starts inside the stretch.
  for (let step = Math.ceil(from * 16); step < to * 16; step += 1) {
    for (const [sound, steps] of Object.entries(BEAT)) {
      if (steps[step % 16] === 'x') drums.play(sound, clock.timeAt(step / 16));
    }
  }
});

The kit plays straight into the speakers. The function of the clock has the shape of the metronome's, with 16 where the 4 was: a step is a sixteenth of a cycle, and Math.ceil() finds the first step that starts inside the stretch. For each step it goes through the four strings and plays the sounds that have an x at that place. step % 16 begins the strings again in every bar.

Read the beat line by line. The bass drum is on every beat. The snare is on beats 2 and 4. The closed hi-hat plays on every other step, and once more on the twelfth. The open hi-hat is on the fifteenth step, and the closed one on the first step of the next bar cuts off what is left of it.

The Play button and the tempo slider stay as they are. Between the slider and draw(), add a pad for every sound:

src/main.ts
// A pad per sound, to hear each one by itself.
const pads = document.querySelector<HTMLDivElement>('#pads')!;
for (const sound of DRUM_SOUNDS) {
  const pad = document.createElement('button');
  pad.textContent = sound;
  pad.addEventListener('click', async () => {
    await audio().resume();
    drums.play(sound, audio().currentTime);
  });
  pads.append(pad);
}

A pad plays its sound now, at currentTime, like the keys of part 1. It does so while the beat runs, too.

At the end of src/style.css, add the rules for the pads. No rule is removed in this part:

src/style.css
.pads {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 6px;
  max-width: 420px;
}

.pads button {
  width: 64px;
  height: 64px;
}

Try it

Click the pads one after the other and compare what you hear with the recipes: the falling pitch at the start of bd, the two layers of sd, the bursts at the start of cp, the three toms from low to high.

  • Click oh and let it ring out. Then click it again and click hh right after it: the ringing stops short. Be quick, the open hi-hat rings for only a third of a second.

  • Click sd a few times. The hits differ a little from one another, because each one takes another piece of the noise.

  • Press Play. Bass drum, snare and hi-hats play the beat, and the pads still work on top of it. Move the tempo slider: the beat keeps its shape at any speed, because it is written in steps and not in seconds.

  • Change the beat in BEAT. Vite reloads the page when you save, so press Play again. Try bd: 'x..x..x...x.x...', or add the line cp: '....x.......x...' to put a clap on top of the snare.

  • Change a recipe. In the line for bd in play(), change the 6, the kick's punch, to 2: the pitch falls much less, and so the knock at the start gets weaker. Change the 0.45, its decay, to 1.5: the low sine rings on for a second and a half.

Put src/main.ts and src/drums.ts back as they were before you go on. The beat is fixed in the code for now. The next part turns rhythms into functions, which can be combined, and swapped while they play.

The app at the end of part 3. Click a pad to hear one sound, or press Play for the beat. The slider sets the tempo.
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.