Graeme Boy

@strangechances

music without audio files

When you are the only person in an Ando Jam, Ando plays quiet music until someone joins. The first version was an MP3. The current version has no audio file at all. A small program writes the music and plays it in your browser, one bar at a time.

This post covers how that works, what we had to get right, and lets you listen to the exact engine live below.

compressed code vs. 569 KB MP3
3.6 KB
A major form at 72 BPM
32 bars
Chromium / Firefox / WebKit match
0.1 dB
target level under speech
−32 LUFS
Live oscilloscope for Soft light synthesized directly in your browser with the Web Audio API LIVE SYNTHESIZER · SOFT LIGHT (NO AUDIO FILE) A major · 72 BPM · ~100 oscillators bells (FM) · strings (3 players, 3 formants) · synthetic 2.6 s room reverb
READY · seed 42 · 0 KB audio fetched
Figure 1. The actual Web Audio synthesizer from Ando Jams running live in this page. Press Play Soft light to hear it synthesized bar by bar; switch to Pass 2+ to hear note swaps and octave lifts without waiting for bar 33.

Why not a file

A file had three problems.

  • Size. The MP3 was 569 KB. That is a lot to ship for something most people hear for a few seconds.
  • The loop. Hold music repeats. After the second pass you start to hear the join, and after the fifth you know every note.
  • It is fixed. A recording cannot be made a little sparser or held a little longer without rendering it again.

The piece we had chosen, which we call Soft light, was already an algorithm. We had written about a dozen candidate tunes as Python scripts that synthesized every sound from scratch, then graded them with a meter: loudness, how much of the sound survives a laptop speaker, and how much energy sits in the harsh range above 5 kHz. Since the winner was rules and arithmetic, the browser could run the same rules live.

Two files: what to play and how it sounds

The code is split in two.

The score decides which notes sound and when. It knows nothing about audio. It holds a thirty-two bar form in A major at 72 beats a minute (in the manner of 1980s Japanese environmental music): a chord for each bar, an eight-note bell figure for each chord, a sparse melody, and two curves that say how full each bar is and how present the strings are.

Some things vary on every pass. Each bell lands a few milliseconds early or late and is struck a little harder or softer than the one before. About half the bars get one very high, very quiet note at a random moment, like light catching water.

The notes themselves are played as written on the first pass. From the second pass on, they change:

score.ts Pass 2+ figure variation
// After the first pass, a bar now and then swaps two notes of its figure.
if (pass > 0 && random() < 0.3) {
  const first = 1 + Math.floor(random() * 7);
  const other = 1 + Math.floor(random() * 7);
  const held = figure[first];
  figure[first] = figure[other];
  figure[other] = held;
}

A melody phrase is left out one time in five, and a melody note sometimes sounds an octave higher.

None of this changes the harmony. A swap only reorders notes the bar already has, an octave shift keeps the same note, and the high notes come from a five-note scale that sits over every chord in the piece. That is what lets it keep varying without drifting out of key.

The engine turns each note into sound with the Web Audio API. There are no samples.

  • Bells. Each one is a pair of oscillators a few cents apart, with a third oscillator modulating their pitch. The modulation fades as the note rings, so the note starts bright and turns pure. Two or three short overtones give the attack its glassy edge.
  • Strings. Each note is three players. Every player is slightly out of tune with the others and has their own vibrato, which only arrives once the bow has settled. Their waveform is shaped with three resonant peaks (520 Hz, 1,150 Hz, and 2,900 Hz), the way a wooden body colors a string.
  • The room. This kind of reverb normally uses a recording of a real space. We generate one instead: two and a half seconds of fading, filtered noise, built once when the music starts.

A slow chorus, an echo three quarters of a beat long, and a gentle compressor finish it.

Thirty-two bar form in A major with fullness and string-swell curves, live bell figure swapper, and three-peak string formant spectrum 32-BAR FORM IN A MAJOR · FULLNESS & STRING SWELL green: strings · ink: fullness I · FIGURE ALONE II · MELODY JOINS III · BRIGHTEST IV · SETTLING 1.0 0.0 A F#m D Esus·E A F#m D Esus·E Bm C#m D E6·Esus A F#m D·E A6·A 8-NOTE BELL FIGURE (SAME CHORD) Bar 9 (A) · Pass 2 STRING BODY FORMANTS (LOG HZ) 520 Hz 1.15 k 2.9 k 200 Hz 1 kHz 5 kHz 8 k rolls off gently before harsh >5 kHz band
Swaps reorder notes inside the same bar · golden dot = pentatonic glint
Figure 2. Top: the exact thirty-two bar chord progression, fullness curve, and string swell from score.ts (tracks live playback when playing). Bottom left: a Pass 2+ bell swap keeping the harmony intact. Bottom right: the three-peak wooden-body resonance curve from engine.ts.

The clock problem

A browser's timers are not accurate enough to play music. In a background tab they fire about once a second, and a Jam is very often in a background tab.

So the engine never plays a note "now". Every 700 milliseconds it asks the score for every bar that starts in the next 4.5 seconds and hands each note to the audio system with an exact start time. The audio system runs on its own clock and plays them precisely, however late the timer was.

engine.ts 4.5 s audio-clock lookahead
const keepAhead = () =>
  music.scheduleUntil(context.currentTime + SCHEDULE_AHEAD_SECONDS);
keepAhead();
const timer = setInterval(keepAhead, SCHEDULE_EVERY_MS);

Code review found the hole in this. If the page freezes for longer than the margin, for example when a laptop sleeps, the engine wakes up several bars behind and schedules all of them at once. Every missed chord sounds together.

The fix is to check each bar against the clock before scheduling it. A bar that has already ended is skipped. Bell notes whose moment has passed are dropped. A held note that should already be sounding starts now and keeps only the time it had left, and its fade in and fade out shrink to fit, so a shortened note still swells instead of clicking.

Comparison of normal 4.5-second lookahead scheduling against a 6.2-second laptop sleep stall, with and without the stillDue fix AUDIO CLOCK VS. BACKGROUND TIMER (0 s TO 12 s) JS timer Audio clock 0 s 3 s 6 s 9 s 12 s
Timers drift in background tabs · audio clock plays every bell on the millisecond
Figure 3. Toggle Laptop sleep (bug) to see three missed bars pile up at wake time, then switch to Laptop sleep (stillDue fix) to see ended bars skipped and the active bar swell smoothly over its remaining duration.

Testing music

The score is easy to test because its only inputs are a bar number and a random source. The random source is seeded, so a test can replay a whole performance. The tests check that the same seed gives the same notes, that later passes differ from the first, and that a varied bar stays inside its chord.

The engine is harder, because it needs a browser's audio system. We wrote a stand-in that plays nothing and records everything it is asked to do. That let us assert, for example, that every change to a volume is scheduled in time order. The click bug above fails that test.

For the sound itself we used the browser. The engine accepts either a live audio context or an offline one, and an offline context renders the music much faster than it plays. We rendered it in Chromium, Firefox, and WebKit, and the three agreed on loudness to within 0.1 dB. The same render gave us the number that sets its volume: the engine comes out at about −18 LUFS, and we turn it down to −32 so it sits under speaking volume.

What it cost

  • Download: 9.4 KB of code, 3.6 KB compressed, loaded the first time music plays. Nothing is fetched after that.
  • Processor: about 100 oscillators sound at once. On an M-series Mac it renders eleven times faster than real time, which is roughly 9% of one core. We have not measured a slow laptop yet.

If you want to hear it, press Play at the top of this page or start an Ando Jam alone and wait a minute. It will not play the same way twice.

If you want procedural furniture music that lives in your macOS menu bar instead of a browser tab, I also built Satie (2.4 MB native Swift and Metal, MIT).