Skip to main content

Lesleh.co.uk

The music in my cat videos is a Swift file

I’ve been making a pixel-art cat that lives on my Mac desktop. It’s called Kitty in the repo and Critters on TikTok, because Kitty is a lame name for a video. The first video I posted was the cat on a plain background, with a generic sound TikTok picked for me, and it flopped. So I made a fancier one, with sound effects on the beat and a chiptune theme to go with it. That also flopped, but fuck it, I’ve done it now. Shout out to the 10 people who liked it, this post is for you.

The music isn’t an audio file, and there’s no library behind it. It’s a Swift script, sound/main.swift, that works out every sample of a 20-second track and writes a WAV file. This is how it works.

Sound is a list of numbers

A track is an array of numbers between -1 and 1, 48,000 of them a second. Twenty seconds of silence is 960,000 zeros, which would still have been more interesting than the sound on the first video.

Each sound is a small function. You give it the time since the sound started and it gives you a number back. To play a sound, the script runs the function for every sample in the sound’s length and adds the results into the track where the sound starts.

for i in 0..<count {
    samples[start + i] += Float(sound(Double(i) / sampleRate) * gain * tail)
}

That’s all mixing is. Two sounds at once is two sets of numbers added together. When the script writes the file, every sample goes through tanh, so stacked sounds round off instead of cracking.

Tune Bass Mix + =

A handful of wave shapes

Every instrument is built from the same few shapes the NES had to work with, which is why it sounds so 8 bit:

  • a square wave, flipping between 1 and -1, for the tune
  • a thinner square wave, high for only a quarter of each cycle, for the chords
  • a triangle wave, which is softer and rounder, for the bass
  • noise, which is just random numbers, for the drums
  • a sine wave for the kick drum

Press a card to hear a bar of each one.

Square the tune Thin square the chords Triangle the bass Noise the clap and hi-hat Sine the kick drum

Shaping each note

On its own, a wave plays at full volume until it stops. To make it sound plucked, the script multiplies it by a number that shrinks as the note plays. This volume shape is called an envelope.

volume = exp(-time * rate)

The rate is how fast the note dies away. Here’s the same middle C at 4 different rates. At 2 it rings on, at 5 it fades like the tune’s notes, and at 80 it’s barely a note at all. Press a row to hear each one.

rate 2 rings on rate 5 the tune rate 20 a pluck rate 80 a tick 0 0.5 s 1 s

Every instrument gets its own rate. The crash rings on at 3, the bass is a pluck at 6, the chords are shorter at 18, and the hi-hat is gone almost before it starts, at 90. A note drops to half volume after 0.69 divided by the rate, so that’s 0.14 seconds for the tune and 8 milliseconds for the hi-hat.

Try a rate of your own below. Letting go of the slider plays the note with it, and a rate of 1 gives you a note that outstays its welcome.

half volume00.5 s1 s

Notes are numbers too

The notes are MIDI note numbers, where 60 is middle C and each step up is a semitone. One line turns them into a pitch:

func midi(_ note: Int) -> Double { 440 * pow(2, Double(note - 69) / 12) }

Note 69 is the A that orchestras tune to, at 440 Hz. Twelve notes up doubles the frequency, which is an octave. Press a key to hear it.

C 60 D 62 E 64 F 65 G 67 A 69 B 71 C 72 61 63 66 68 70 12 notes up is an octave, at double the frequency middle C A at 440 Hz

So the whole score fits in a few arrays:

static let chords = [[65, 69, 72], [60, 64, 67], [62, 65, 69], [58, 62, 65], [62, 67, 70], [60, 64, 70]]
static let chordNames = ["F", "C", "Dm", "Bb", "Gm", "C7"]
static let roots = [53, 48, 50, 46, 43, 48]

The tune is a list of notes for each bar, one slot for every half-beat, with nil for a rest.

The chords everyone uses

It’s 120 beats a minute in F major, with a bar every 2 seconds. The first 8 bars play F, C, D minor and B flat, twice. In numerals that’s I, V, vi, IV, which is the most common chord progression in pop. “Let It Be” uses it, so does “Someone Like You”, and the Axis of Awesome have a whole comedy song about how many hits share it. It sounds familiar straight away, which is what you want from 20 seconds of video.

The tune is about as simple as tunes get. Each bar hits a note from the chord, steps down to another one, then does a little turn up and back. It isn’t taken from any song in particular, but with something this simple I can’t promise nobody has written the same thing.

The chords don’t play as chords either. They play as an arpeggio, one note at a time, 8 notes a second, running up the chord’s three notes and the same three an octave higher, then partway back down. The bass plays each chord’s root note and bounces between it and the note an octave above.

The drums are a falling sine and some noise

The kick drum is a sine wave that drops from 160 Hz to 45 Hz in 80 milliseconds and fades out fast. That falling pitch is most of what makes it sound like a kick.

The clap and the hi-hat are both noise. The clap is a short burst on beats 2 and 4, and the hi-hat is a 50 millisecond tick between the beats. Both take the difference between each random number and the one before, which cuts out the low end and makes them thinner and brighter.

The noise comes from a tiny random number generator with a fixed starting value, so every clap is the same clap.

The breakdown and the drop

Every video has its payoff at 14 seconds, and the music builds to it. At 13 seconds the drums, bass and tune stop, and the chords switch from the thin square wave to the softer triangle. A noise sweep rises underneath, and a snare roll gets louder into the drop. At 14 seconds there’s a crash and everything comes back in.

The script also writes each instrument to its own file, and on their own they all sound pretty basic. It’s only stacked up that it turns into something. Play it below and switch the instruments on and off, or press the timeline to jump to the drop.

Tune Chords Bass Drums 0 10 20 s 13 s breakdown 14 s drop
0:00

This turned out to be the most useful part for TikTok, because every video gets cut to it. The cat swats on the beat, the reveal goes on the drop, and the sound effects land in time with the music.

Making it loop

TikTok replays videos on a loop, so the end has to lead back into the start. The first version didn’t. The chords run in a 4-bar pattern, but the track is 10 bars long, so it stopped halfway through the pattern and started again from the top. The video looped fine, the music didn’t.

The fix was to swap the last 2 bars for a turnaround, G minor then C7. C7 pulls hard towards F, which is where the track starts, and the tune climbs A, B flat, B into the C that opens bar 1. There’s also a short noise rise in the last half-second, so every replay starts on the crash.

4-bar pattern again turnaround F I C V Dm vi Bb IV F I C V Dm vi Bb IV Gm ii C7 V7 C7 pulls back into F, and the loop starts again

The clicks

The bass clicked between notes. A speaker follows the numbers, so a sudden jump from one sample to the next jerks the speaker, and you hear that as a click. A triangle wave starts at its peak, so every bass note started with a jump, and every note was cut off mid-wave, which is another one. At bass note changes the samples jumped 35 times further than anywhere inside a note.

The fix is a 3 millisecond fade at each end of every note. That’s far too short to hear as a fade, but it’s enough to stop the jump. Press each version to hear the difference.

Before click click With 3 ms fades

Phone speakers

A couple of things only matter because the music ends up coming out of a phone. Phone speakers barely play anything below about 100 Hz, so the bass sits higher than you’d expect, otherwise it disappears. The final mix is set to -14 LUFS with peaks kept 2 dB under full scale, because AAC encoding pushed an earlier version over and that can crackle on some phones. The music also sits at half volume under the sound effects, because it was drowning out the swats. Nobody’s watching a cat video for the bass line.

Seeing how it fits together

The latest TikTok is about the music itself. It plays each part on its own under a piano roll that lights up the notes as they play, then all of them together through the drop.

The synth, the score and the mixing come to about 200 lines of Swift. If you want to poke at it, it’s all in the Kitty repo. View counts, like 20 seconds of silence, are mostly zeros.