DEV Community

Cover image for What Makes a Music Box Go 'Tink' (and How to Fake It in Web Audio)
yang changjiang
yang changjiang

Posted on Edited on Originally published at soundtool.tools AI-assisted

What Makes a Music Box Go 'Tink' (and How to Fake It in Web Audio)

What Makes a Music Box Go 'Tink' (and How to Fake It in Web Audio)

A music box is a simple machine. A brass cylinder with pins spins against a steel comb. The teeth are cut to different lengths, so each one rings at its own pitch and dies out fast. Long teeth sing low, short teeth sing high. The melody is just the arrangement of pins.

I spent a while rebuilding that machine in a browser: an 18-note virtual music box, C5 to F6, the standard movement size for souvenir boxes. The hard part was never the notes. It was the timbre.

The virtual music box: walnut box, steel comb, pin cylinder and crank

The fourth partial is the whole trick

Pluck one tooth on a real box and you hear three things: a bright fundamental, a very strong fourth partial (four times the fundamental frequency), and a fast decay. The fourth partial is what makes it metallic instead of flutey. A plain sine wave sounds like a test tone. Add its fourth partial, let both decay quickly, and it sounds like a music box.

The voice is three oscillators into one gain:

function playTooth(n, when) {
  const ctx = getCtx();
  const t = when === undefined ? ctx.currentTime : when;
  const f = freqs[n];

  const g = ctx.createGain();
  g.gain.setValueAtTime(0.42, t);
  g.gain.exponentialRampToValueAtTime(0.001, t + 1.6);

  // fundamental
  const o1 = ctx.createOscillator();
  o1.type = 'sine'; o1.frequency.value = f;

  // the signature: 4th partial, strong but short-lived
  const o2 = ctx.createOscillator();
  o2.type = 'sine'; o2.frequency.value = f * 4;
  const g2 = ctx.createGain();
  g2.gain.value = 0.4;
  g2.gain.exponentialRampToValueAtTime(0.001, t + 0.9);

  // a faint shimmer one octave above that, gone in 300ms
  const o3 = ctx.createOscillator();
  o3.type = 'sine'; o3.frequency.value = f * 8;
  const g3 = ctx.createGain();
  g3.gain.value = 0.06;
  g3.gain.exponentialRampToValueAtTime(0.001, t + 0.3);

  // steel comb has no low-end mud
  const hp = ctx.createBiquadFilter();
  hp.type = 'highpass'; hp.frequency.value = 300;

  o1.connect(g); o2.connect(g2); g2.connect(g);
  o3.connect(g3); g3.connect(g);
  g.connect(hp); hp.connect(ctx.destination);

  o1.start(t); o2.start(t); o3.start(t);
  o1.stop(t + 1.7); o2.stop(t + 1.0); o3.stop(t + 0.4);
}
Enter fullscreen mode Exit fullscreen mode

The decay envelope does most of the work. The fundamental hangs around for 1.7 seconds; the fourth partial is gone in under one. That gap is the "tink" followed by a fading body. The 300 Hz highpass keeps it from sounding like a soft pad. Music boxes are bright. There's no warmth to protect.

Eighteen teeth, eighteen frequencies:

const teeth = ['C5','C#5','D5','D#5','E5','F5','F#5','G5','G#5','A5','A#5','B5','C6','C#6','D6','D#6','E6','F6'];
const freqs = {};
teeth.forEach(n => {
  const m = n.match(/([A-G])(#?)(\d)/);
  const base = {C:0,D:2,E:4,F:5,G:7,A:9,B:11}[m[1]] + (m[2] === '#' ? 1 : 0);
  const oct = parseInt(m[3]);
  freqs[n] = 440 * Math.pow(2, (base - 9) / 12 + oct - 4);
});
Enter fullscreen mode Exit fullscreen mode

Making it look like a music box, not a keyboard

My first version rendered the 18 teeth as vertical bars in a row. It worked, and it was wrong. A comb isn't a keyboard: it's one steel plate with teeth cut into it, hanging over a cylinder. So I redrew it:

  • One metal spine across the top, teeth hanging down from it. Long teeth on the left (C5, 98 px), stepping down to short teeth on the right (F6, 46 px). Graduated length is the whole instrument.
  • A brass pin cylinder under the teeth tips. The pins are pure CSS, a radial-gradient dot pattern on an 11×12 px tile repeated over a rounded gradient bar.
  • A crank on the right, walnut box, red felt, lid propped open. All divs and gradients. No images, no canvas.

The rotation is the fun part. No WebGL. A rotating cylinder is just the pin pattern's background-position scrolling in a loop:

@keyframes mbspin {
  from { background-position: 0 0; }
  to   { background-position: 0 120px; }
}
Enter fullscreen mode Exit fullscreen mode

The dot tile repeats every 12 px, so 120 px is exactly ten revolutions. Seamless loop, for free. When you pluck one tooth, the cylinder takes a quick quarter turn instead (0 to 32 px in 0.38 s). Re-triggering the same CSS animation per note needs the reflow trick: remove the class, force layout with void el.offsetWidth, add it back. The crank spins while the demo plays, 0.85 s per turn.

Close-up: comb teeth hanging over the brass pin cylinder

Recording without a server

Record stores note events as {f, t} pairs, then replays them through the same voice graph into an OfflineAudioContext:

const off = new OfflineAudioContext(1, len, 44100);
recNotes.forEach(rn => {
  const t = rn.t;
  // ...same gain ramps, same three oscillators, same highpass...
  o1.start(t); o2.start(t); o3.start(t);
  o1.stop(t + 1.7); o2.stop(t + 1.0); o3.stop(t + 0.4);
});
off.startRendering().then(buf => {
  const wav = encodeWav(buf);
  const blob = new Blob([wav], { type: 'audio/wav' });
  download.href = URL.createObjectURL(blob);
});
Enter fullscreen mode Exit fullscreen mode

The WAV encoder is about 40 lines: RIFF header, fmt chunk, PCM16 samples. Because the render runs the same oscillator graph, the export sounds exactly like what you heard live. Nothing is uploaded anywhere.

Details that mattered more than expected

Plucking fires on mousedown and touchstart, not click. A music box plucks at the press, not the release, and click adds a delay you can feel in fast runs. preventDefault stops the double fire on touch.

Keyboard support maps one key per tooth in pitch order (A W S E D F T G Y H U J K O L P ; '), same layout as the piano tools on the site, so muscle memory carries over.

AudioContext gets created lazily and resumed on the first gesture. Browsers require a gesture before audio starts, and you don't want a suspended context eating your first pluck.

The demo melody is Brahms' Lullaby. Public domain, and the classic music-box tune since 1868.

Fourteen languages, one comb

The tool ships in 14 languages, including RTL (Arabic) and no-space scripts (Thai, Japanese). UI strings come from a per-language file loaded at runtime. The instrument itself is language neutral. The comb renders with dir="ltr" internally so low-to-high tooth order stays physically correct on RTL pages.

What I'd change next

The voice is a model, not a sample. It's small, it loads instantly, and everyone hears the same sound, which is why I kept it synthesized. A version two would add a slightly inharmonic second partial (real teeth aren't perfect sines) and per-tooth detune so chords beat naturally. A sampled comb through a convolution reverb would be closer again. I don't know that I'd want that tradeoff: a few kilobytes of JavaScript vs a sample library.

Try it: soundtool.tools/virtual-music-box. Click the teeth, hit the demo, record something, download the WAV.

I built this tool. It's part of soundtool.tools, a set of browser-based audio utilities.

Top comments (0)