⚠ ⚠ You are viewing this page in 1998 MODE. Some modern niceties have been switched off on purpose. Return to the present ➜
老博客 onyx.xn--fiqs8s/a-chiptune-theme-without-a-single-mp3

A chiptune theme without a single MP3

Press the ♪ button in the corner. That is the whole soundtrack: oscillators, a gain node, and about forty lines of JavaScript. Nothing is downloaded.

How it works#

const ctx = new AudioContext();
const osc = ctx.createOscillator();   // square wave = 8-bit heart
osc.type = 'square';
osc.frequency.value = 523.25;         // C5
osc.connect(ctx.destination);
osc.start();

That plays one note forever. To get a tune you need a sequencer, a short note table, and a lookahead scheduler so the timing does not drift when the tab is busy.

const MELODY = [
  [0, 523.25], [1, 659.25], [2, 783.99], [3, 659.25],
  [4, 587.33], [5, 493.88], [6, 440.00], [7, 493.88],
];

function schedule(step = 0) {
  const [beat, freq] = MELODY[step % MELODY.length];
  const at = ctx.currentTime + beat * 0.25;
  playNote(freq, at, 0.24);
  setTimeout(() => schedule(step + 1), 260);
}

Why bother?#

Because an autoplaying

📶 📶 Connecting at 56,000 bps… /a-chiptune-theme-without-a-single-mp3 hits: 2298 online: 3