2026-06-11·Sanchez

Zero Sound Files — Synthesizing SFX with Web Audio

I kept external assets to a minimum throughout the rebuild.
Only the background music (BGM) uses mp3s; the sound effects (SFX) use no files at all — every effect (collect, jump, hit, combo) is synthesized on the spot with the Web Audio API.

There are only two basic tools: an oscillator (which generates a waveform) and gain (volume).
Add a starting frequency, a duration, a waveform type, and an envelope that decays the volume toward zero over time, and you've got one short sound effect.
I reuse this single function for everything.

function blip(freq, dur, type, gain = 0.15, slide = 0) {
  const c = ac(); // lazily-created AudioContext (browser/SSR guard)
  const o = c.createOscillator();
  const g = c.createGain();
  o.type = type;
  o.frequency.setValueAtTime(freq, c.currentTime);
  if (slide !== 0) // glide the pitch over the duration
    o.frequency.exponentialRampToValueAtTime(freq + slide, c.currentTime + dur);
  g.gain.setValueAtTime(gain, c.currentTime);
  g.gain.exponentialRampToValueAtTime(0.0001, c.currentTime + dur); // envelope
  o.connect(g).connect(c.destination);
  o.start();
  o.stop(c.currentTime + dur);
}

I split the timbres: a low sine wave for jumps, a gritty sawtooth for taking a hit.
My favorite detail is the collect sound — the pitch rises as your combo climbs.

export const playCollect = (combo: number) =>
  blip(520 + Math.min(combo, 24) * 40, 0.18, "triangle", 0.18, 120);

520 + min(combo,24)*40Hz.
Grab one and it's 520Hz; as the combo builds it steps up a notch at a time and caps out at the ceiling.
When you collect a streak in a row, the pitch trickles upward — and that rising feel was more thrilling than the combo itself.
There's no way I'd have gotten that satisfaction from replaying the same canned sound.

The code above is the version from the June 2026 rebuild.
In November 2026 the collect sound moved to a C major pentatonic scale.

Here is the current code.

// lib/game/pitch.ts
export const midiToHz = (midi: number) => 440 * 2 ** ((midi - 69) / 12);

// one octave every five steps: C D E G A = semitones [0, 2, 4, 7, 9]
export function pentatonicHz(step: number, baseMidi = 60) {
  const octave = Math.floor(step / 5);
  const degree = ((step % 5) + 5) % 5;
  return midiToHz(baseMidi + 12 * octave + [0, 2, 4, 7, 9][degree]);
}

// combo 1 = step 0 (C4), combo 16 = step 15 (C7), flat above that
export const collectStep = (combo: number) =>
  Math.max(0, Math.min(15, combo - 1));

// lib/game/audio.ts
export const playCollect = (combo: number) => {
  const hz = pentatonicHz(collectStep(combo));
  blip(hz, 0.18, "triangle", 0.18, hz * 0.06); // slide is 6% of the pitch
  if (collectSparkle(combo)) // from combo 17
    blip(hz * 2, 0.08, "sine", 0.06, 0, 0.03); // sparkle an octave up
};

Combo 1 is C4 (about 262Hz), and every five carrots in a row lift it an octave until combo 16 reaches C7 (about 2,093Hz).
Past that the pitch stops climbing and a small sine an octave higher sparkles on top.
The slide changed too, from a fixed +120Hz to 6% of the pitch.

The old formula climbed in equal 40Hz steps.
But a semitone gets wider as the pitch goes up.
Around 520Hz, 40Hz is wider than a semitone; around 1,400Hz it's less than half of one.
So the steps landed on notes outside any scale.
The five notes of a pentatonic scale never clash with each other, so eating carrots quickly sounds like a short melody.

I also covered the browser environment check.
If window or AudioContext is missing, every function quietly falls back to a no-op.
That keeps things from blowing up under SSR or unsupported environments.

That wraps up the rebuild dev log.
The takeaway is simple — even with zero sound-effect files, code alone was enough to make sounds that feel cute and satisfying to play.

A sixth argument makes chords

One blip produces one tone.
But the game has an unlock fanfare and a rising arpeggio.
Rather than write new functions, one more argument covered it — delay.

const t0 = c.currentTime + delay; // everything schedules against this

Web Audio lets you schedule an oscillator's start and stop ahead of time.
So calling blip several times with different delay values plays the notes in order on its own.
No setTimeout required.
A JavaScript timer slips whenever the main thread is busy; audio scheduling is kept sample-accurate on the audio thread.
Frames can drop and the fanfare still doesn't wobble.

The unlock fanfare looks like this.

export const playUnlock = () => {
  blip(523, 0.1, "triangle", 0.14);            // C
  blip(659, 0.1, "triangle", 0.14, 0, 0.08);   // E, 0.08s later
  blip(784, 0.1, "triangle", 0.14, 0, 0.16);   // G
  blip(1047, 0.25, "triangle", 0.16, 0, 0.24); // high C, held longer
};

523, 659, 784, 1047 Hz is C–E–G–C: a plain C major arpeggio.
Only the last note stretches to 0.25s to close it out.
It's closer to writing sheet music than writing code.

Twenty-three sounds

The game currently has twenty-three effects.
Most are the same blip with different arguments; the few that need texture mix in noise, covered further down.

EffectFrequencyWaveformCharacter
Jump220Hzsineshort and low, slides up
Collect262Hz+ (C4)triangleclimbs the pentatonic scale with the combo
Near miss880Hzsine0.08s, barely there
Hit140Hzsawtoothslides down
Trampoline180Hzsine+340Hz — a "boing"
Booster330Hzsawtooth+480Hz, steep climb
Gem880Hztrianglelayered with 1320Hz, bright
Game over330Hztriangle−180Hz, falling
Fever start220→880Hzsawtoothswells upward over 1s
Fever end660Hztriangle−330Hz, falling
Layer chime659·988Hzsine·triangleevery 100m, two notes plus a sparkle
Slam whoosh1200→300Hznoise + sinethe sound of dropping
Rock crunch90Hznoise + squarea dull thud sliding down

A rule shows up. Good things go up, bad things go down. Collect, trampoline, booster, and gem all slide upward; hits and game over fall.
The waveforms split too — sine and triangle for soft events, sawtooth and square for harsh ones.

The sounds added later follow the same rule.
Fever start rises and Fever end falls.
The slam whoosh falls because Mocha is literally falling.

That isn't music theory, it's a convention people already know.
Nobody has to be told that a rising tone means it went well.
Synthesizing sound turns that rule into a number rather than a filename, which turned out to help the design: deciding on a new effect starts and mostly ends with "is this a good thing or a bad thing," and that fixes the sign of slide.

An exponential ramp can't reach zero

There's a reason the envelope ramps to 0.0001 rather than 0.

An exponential ramp cannot reach zero by definition — passing zero throws.
So it converges to something too quiet to hear instead.
Using a linear ramp avoids that but makes notes end with an audible click: human hearing is logarithmic, so a linear fade sounds like it vanishes all at once at the end.
Exponential decay is what sounds natural.

slide needs the same kind of guard.

o.frequency.exponentialRampToValueAtTime(Math.max(40, freq + slide), t0 + dur);

Without Math.max(40, ...), a negative slide like the hit sound can drive the target frequency to zero or below and throw for the same reason.
The guard wasn't there at first, and low notes with a big downward slide would cut off mid-sound and log an error.

An AudioContext is born locked

Browsers block audio until the user has interacted with the page, so a freshly constructed AudioContext usually starts out suspended.

if (ctx.state === "suspended") void ctx.resume();

That's why ac() checks and wakes it on every call.
By the time the first effect plays, the user has already tapped to start the game, so the resume() goes through.
Creating the context lazily — on the first sound rather than at module load — is part of the same fix: build it early and it sits locked, swallowing the first sound.

What skipping files cost, and bought

The upside was clear.
Twenty-three sound effects weigh zero bytes.
Nothing downloads, so nothing delays the first sound.
And most of all, a dynamic sound like a pitch that climbs with the combo simply isn't possible from files — you're not going to record 16 separate collect sounds plus a sparkle layer.

There's a cost too.
Textured sounds — footsteps, soil crumbling — don't come out of an oscillator.
At first I figured that was the domain of noise and filters, and that once you're there you may as well ship files.
So at the rebuild, every effect was in the "beep" family.

Adding Fever and the slam in November 2026 changed that.
The game needed sounds for obstacles breaking and for dropping, and instead of files I wrote one more function for noise.

let noiseBuf: AudioBuffer | null = null;

function noise(dur: number, gain: number, lowpassHz: number, delay = 0) {
  const c = ac();
  if (!c) return;
  if (!noiseBuf) { // one second of white noise, built once and reused
    const buf = c.createBuffer(1, c.sampleRate, c.sampleRate);
    const d = buf.getChannelData(0);
    for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
    noiseBuf = buf;
  }
  const t0 = c.currentTime + delay;
  const src = c.createBufferSource();
  const f = c.createBiquadFilter();
  const g = c.createGain();
  src.buffer = noiseBuf;
  f.type = "lowpass";
  f.frequency.value = lowpassHz; // lower means duller
  g.gain.setValueAtTime(gain * volume, t0);
  g.gain.exponentialRampToValueAtTime(0.0001, t0 + dur);
  src.connect(f).connect(g).connect(master(c));
  src.start(t0);
  src.stop(t0 + dur);
}

The buffer is built once for a reason.
Creating a new one every time while carrots are being eaten back to back keeps the garbage collector busy and makes frames hitch.
The rock crunch is 0.18 seconds of noise with everything above 700Hz cut, layered over a 90Hz square-wave thud.
The whoosh is noise under 2,500Hz with a sine falling from 1200 to 300Hz on top.
That turned out to be enough texture without files.
I stopped short of realistic sound, though; this much suits a casual tone.

More sounds called for one more piece.
So that collect sounds firing five times a second don't distort when a Fever riser and a crunch land on top of them, every effect now goes through a single DynamicsCompressor instead of straight to c.destination.
With a −10dB threshold and a 12:1 ratio it works as a limiter.
A compressor automatically adds makeup gain to its output, which would make every quiet sound below the threshold about 4dB louder, so a 0.607× gain after it brings the level back down.

Background music being the one exception, shipped as mp3, follows from the same limit.
You don't synthesize a twelve-track soundtrack.

Try it yourself →