Catchy 8-bit music
Outside of work, I spend a fair amount of time messing around with music. One of my favorite formats is 8-bit game music: four tiny channels, no real reverb, no lush samples, just raw waveforms and strict polyphony limits. When you take away production tricks, everything comes down to melody, rhythm, and how the parts fit together.
With three synth voices (lead, harmony, bass) and a noise drum track, the hard part of generating music algorithmically is not the synthesis. Picking random notes from a scale does not sound like music; it sounds like someone knocking over a xylophone. Consistently producing tunes you might actually hum requires encoding a handful of small, concrete musical rules.
Getting the 8-bit sound right
Before generating notes, the synth has to sound like an 8-bit chip rather than a sterile browser beep. Two small details do most of the heavy lifting.
First, classic NES leads get their bite from pulse waves with narrow duty cycles (12.5% and 25%, not just a 50% square wave). You can compute the Fourier coefficients for any duty cycle directly:
func pulseWave(duty float64) (re, im []float32) {
const N = 64
re, im = make([]float32, N), make([]float32, N)
for k := 1; k < N; k++ {
kf := float64(k)
re[k] = float32((2 / (kf * math.Pi)) * math.Sin(kf*math.Pi*duty))
}
return re, im
}
Second, 8-bit percussion is not smooth white noise. The NES APU generated noise with a 15-bit linear-feedback shift register (LFSR), which produces a slightly metallic, crunchy texture. Filling a sample buffer with the same bit-shift loop takes just a few lines:
func noiseBuffer(n int) []float32 {
buf := make([]float32, n)
var lfsr uint16 = 1 // NES-style 15-bit LFSR
for i := range buf {
bit := (lfsr ^ (lfsr >> 1)) & 1
lfsr = (lfsr >> 1) | (bit << 14)
if lfsr&1 == 1 {
buf[i] = 1
} else {
buf[i] = -1
}
}
return buf
}
Passing that buffer through high-pass filters with short exponential envelopes gives you snares, closed hats, and open hats; pairing a fast pitch-swept triangle wave (170 Hz down to 42 Hz) with a tiny noise click gives you the kick.
Start with a shared harmonic skeleton
When generating a new tune, start by picking a root, a mode (major, minor,
dorian, or mixolydian), and a chord progression from a small bank of
well-known patterns (things like I-V-vi-IV, i-VI-III-VII, or two-chord
Dorian vamps). Every melodic voice queries the same chordAt(gen, step)
function so the lead, harmony, and bass always agree on what chord is active at
any 16th-note step.
If you start from a hand-written melody and only want to generate a bassline or harmony to go with it, you can build a 12-bin pitch-class histogram of the existing notes and score every major and minor key, giving extra weight to the tonic and fifth, to infer the key automatically.
Catchy melodies come from motifs, not notes
The biggest leap in quality comes from separating a melody into motifs and form. A motif is an 8-step rhythm paired with a pitch contour, stored as relative scale-step deltas rather than fixed notes.
The rhythm generator biases hits toward on-beats (60% chance of picking steps
2, 4, 6 vs off-beats 1, 3, 5, 7) and picks a density based on the lead
style (lyrical, arpeggio, driving, or bouncy). The contour generator
then walks up and down the scale with one classic counterpoint rule baked in:
gap-fill. Whenever the melody makes a leap of 3 or more scale steps, the
very next note must step back in the opposite direction:
func genContour(n int, st LeadStyle) []int {
out := make([]int, 1, n)
dir := 1
if chance(0.5) {
dir = -1
}
prev := 0
for i := 1; i < n; i++ {
var mag int
if prev >= 3 || prev <= -3 {
dir = -sign(prev)
mag = pick(1, 1, 2) // a leap is followed by a step back
} else {
if chance(0.25) {
dir = -dir
}
mag = weighted(st.Mags)
if mag == 0 && prev == 0 {
mag = 1 // avoid 3 identical pitches in a row
}
}
prev = mag * dir
out = append(out, prev)
}
return out
}
That single rule eliminates most of the aimless wandering you hear in naive random walks.
Once we have a motif mA1, we build a second half mA2 (often by mutating
just one contour step of mA1 by ±1) and arrange bars into a recognizable
song form, such as A, A2, B, A2. Repetition makes a tune stick in your head;
the B bar introduces contrast by shifting the starting register up by 2 to 4
scale degrees.
Four small rules that make phrases feel written
A motif repeated verbatim over changing chords still sounds mechanical. Four small passes turn it into a phrase:
- Directional chord-tone snapping. On strong beats (
step % 4 == 0) or long notes (dur >= 3), the current scale position snaps to the nearest chord tone in the direction of motion. Searching forward in the direction the melody was already moving keeps an upward step from collapsing back onto the previous pitch. - Question and answer cadences. At the end of each bar,
cadence()clears the last 2 or 3 steps and holds the final note to leave a breath. OnAbars, that note lands on a non-tonic chord tone (an open “question”); onA2and the final bar, it resolves to the tonic (a closed “answer”). - Pickup notes. Before the next phrase starts, there is a 45% chance of inserting 1 or 2 stepwise lead-in notes approaching the next bar’s first pitch from the side the melody is coming from.
- A single climax. A final pass finds the highest non-cadence note in the
Bbar and lifts it to a new peak chord tone above everything else in the loop. Giving a 4-bar loop one clear high point makes it feel intentional.
Voice-led harmony and the fake-reverb echo
The harmony channel has two jobs: fill out the chords without fighting the lead, or give the lead space.
For arpeggios (up, updown, alberti), stabs, and held chords, voicing()
checks all three triad inversions and picks the one whose average pitch is
closest to the previous chord’s average pitch:
func voicing(chord [3]int, prevMean float64) [3]int {
var best [3]int
bestDist := math.Inf(1)
for k := 0; k < 3; k++ {
r := lowestAbove(chord[k], 52)
t := lowestAbove(chord[(k+1)%3], r+1)
f := lowestAbove(chord[(k+2)%3], t+1)
dist := math.Abs(float64(r+t+f)/3.0 - prevMean)
if f > 79 {
dist += 100
}
if dist < bestDist {
best, bestDist = [3]int{r, t, f}, dist
}
}
return best
}
Smooth voice leading keeps the accompaniment from jumping wildly across octaves when chords change.
My favorite harmony mode, though, is echo: it copies the lead notes delayed
by 2 to 4 steps, drops them an octave, and lowers the volume. Early game
composers used this exact trick on the NES and Game Boy to fake delay and
reverb using their second pulse channel.
Locking the bass to the kick
Finally, the bass runs on a triangle wave (classic NES) or sawtooth and picks
from patterns like octave pumping, root-fifth walking, or kicklock, which
reads directly from the generated kick drum array so the bass hits in lockstep
with the percussion. Right before a chord change, it has a 50% chance of
dropping a chromatic or diatonic approach note (nextRoot - 1 or
nextRoot - 2) on the last 16th note to pull the ear into the next bar.