Algorithms · Counting & data
Audio fingerprinting
How Shazam names a song from ten noisy seconds. Forget the whole song. Remember a few loud peaks, and how far apart they are.
The problem
You're in a loud bar. A song comes on, you hold up your phone, and ten seconds later Shazam names it. The clip has chatter, clinking glasses and a cheap phone microphone mixed in with the music.
Shazam has to match that messy clip against a huge catalogue of clean recordings, and it has to do it fast. Avery Li-Chun Wang's 2003 paper, An Industrial-Strength Audio Search Algorithm, describes the method.
The obvious way
Compare the recording's raw samples against every song, sliding along until they line up. It breaks the moment anything differs. Noise changes nearly every sample, so the clip never equals any stretch of the original, and even a tiny mismatch ruins an exact comparison. Sliding over a whole catalogue would be slow too.
The clever idea
Think of recognising a friend in a crowd photo. You don't compare every pixel. You spot a few landmarks, like the tall hat next to the red scarf. Shazam turns audio into a spectrogram, a picture of which pitches are loud at each moment, and keeps only the strongest peaks. That sparse dot pattern is a constellation map. Noise rarely erases the loudest peaks, so many survive.
Next, pair nearby peaks and hash each pair as (frequency1, frequency2, time gap). To match a clip, look up its hashes in an index. The real song gets many hits that all agree on the same time offset, while accidental hits scatter. So the app counts votes per (song, offset).
How the code does it
The hash function pairs every peak with peaks 1 to 3 steps later, and the index files each hash under the song and time it came from. The clip is then damaged on purpose: some peaks dropped, some noise added. Fewer than half the original pairs survive, but some do.
The obvious approach finds the clean clip but returns "no match" for the noisy one. The clever approach looks up each surviving hash, and the vote key is (song, offset). Blues collects many votes on a single offset of 20, while the other songs only get stray collisions. The bar chart shows the gap.
Trade-offs
You pay up front: every song must be analysed and indexed, and the index takes memory. Matching also needs enough surviving peaks, so a clip that is mostly noise, or a heavily changed version like a remix at a new tempo, may not match. Don't use it to find songs that merely sound similar. It finds the same recording.
Where else you'll see it
Hash an index, then vote on agreement. The same pattern shows up in near-duplicate image search and in DNA sequence matching, where messy fragments are matched against a big reference.
Why does Shazam vote on (song, offset) instead of just counting hash matches per song?
- Offsets make lookups faster
- Real matches agree on one offset; accidental matches scatter
- Offsets remove the need for hashes
Show the answer
Real matches agree on one offset; accidental matches scatter. Any song can share a few random hashes with the clip. Only the true song has many matches that all line up at the same time offset.
- Change 0.3 to 0.7
- Raise noise range(8) to range(60)
- Change
<= 3to<= 1
The code
Python, with what each line means beside it. It compares the clever way with comparing raw audio samples.
import randomBring in the random toolsrandom.seed(7)Fix the dice so results repeat songs = {n: [(t, random.randint(1, 40)) for t in range(60)]Build each song as (time, pitch) peaks for n in ["Aria", "Blues", "Cumbia"]}Name them Aria, Blues and Cumbia def hashes(peaks):Define a function that hashes peak pairs return [((f1, f2, t2 - t1), t1)Each pair becomes pitch, pitch, time gap for t1, f1 in peaks for t2, f2 in peaks if 0 < t2 - t1 <= 3]Only pair peaks up to 3 steps apart index = {}Start an empty indexfor name, peaks in songs.items():Visit every song for h, t in hashes(peaks):Visit every hash in it index.setdefault(h, []).append((name, t))File the hash under song and time clip = [(t - 20, f) for t, f in songs["Blues"] if 20 <= t < 30]Cut a 10-step clip from Bluesheard = [p for p in clip if random.random() > 0.3]Randomly drop about 30% of peaksheard += [(random.randint(0, 9), random.randint(1, 40)) for _ in range(8)]Sprinkle in 8 random noise peaks def naive(sample):Define the obvious exact-match search for name, peaks in songs.items():Try each song for s in range(50):Try each possible start time window = [(t - s, f) for t, f in peaks if s <= t < s + 10]Cut a window of that song if sorted(window) == sorted(sample):If the window equals the sample exactly return nameReport that song return "no match"Otherwise give up show({"clean clip": naive(clip), "noisy clip": naive(heard)}, "Obvious way")Show what exact matching finds votes = {}Start empty vote countsfor h, t in hashes(heard):For each hash heard in the clip for name, song_t in index.get(h, []):Look up every song that has it key = (name, song_t - t)Compute the time offset it implies votes[key] = votes.get(key, 0) + 1Add one vote for that song and offset best = {n: max([v for (s, _), v in votes.items() if s == n], default=0) for n in songs}Keep each song's biggest offset tallyshow(list(best.values()), "Votes at best offset: Aria, Blues, Cumbia")Draw those tallies as barsprint(best)Print the numbers- pair hash lines 7–9Each key stores two pitches and the gap between them. It ignores absolute time, so it survives starting the clip mid-song.
- why naive fails lines 23–24One dropped or extra peak makes the lists unequal, so exact comparison rejects the right song.
- offset vote lines 33–34A true match implies the same song_t minus t every time. Accidental hits land on scattered offsets.
Read more
- ee.columbia.edu: Audio fingerprinting
- Ask Bento: What is a Fourier transform?
- Ask Bento: How do hash tables work?
- Ask Bento: How does reverse image search work?
Run it. Then change it.
The code runs right in the page and draws as it goes. Free, nothing to install.