Code and Gravity

How can a bouncing ball play a song?

The ball does not choose the notes. The melody is stored as a list, and every bounce plays the next note on the list. The sound is then snapped to the beat so it sounds like a person playing.

A list of notes

Each melody is saved as a list of MIDI note numbers, one number per note. Middle C is 60, and each step up is one semitone. Twinkle Twinkle starts 60, 60, 67, 67, 69, 69, 67.

One bounce, one note

The simulation runs 60 times a second. When the ball hits a wall, the engine records a "note" event and plays the next number from the list. The event is stored with the frame it happened on.

Why it sounds in time

A raw bounce can land anywhere in time, which sounds sloppy. When we render the sound, every note is moved to the nearest sixteenth-note slot of the backing track. The tune stays in order, but it lines up with the drums and chords.

Why it is hard to guess

In a real song the rhythm is part of the tune. Here the rhythm comes from the shape of the container and the ball speed. You only get the order of the pitches, so familiar songs can sound strange until the pattern clicks.

Questions

Is the music pre-recorded?
No. The backing track and every bounce note are synthesised in the browser from simple waveforms.
Can the ball play any song?
Yes, any melody that can be written as a list of notes. Songs in the public domain, such as Twinkle Twinkle, Jingle Bells and Fur Elise, are the safest to use.

Try it: open in the sandbox →

Sources: MIDI (Wikipedia)

By Code and Gravity · 2026-10-23

More to learn