Lesson 3 of 6 · 2 min
A complete matcher
This runs here with generated tunes.
import numpy as np
from collections import Counter, defaultdict
from scipy.signal import spectrogram
from scipy.ndimage import maximum_filter
RATE = 8000
def peaks(audio):
_, _, s = spectrogram(audio, RATE, nperseg=1024, noverlap=512)
s = np.log(s + 1e-10)
top = (s == maximum_filter(s, size=15)) & (s > np.percentile(s, 98))
f, t = np.nonzero(top)
order = np.argsort(t)
return list(zip(t[order], f[order]))
def hashes(audio):
p = peaks(audio)
for i, (t1, f1) in enumerate(p):
for t2, f2 in p[i + 1:i + 8]:
if 0 < t2 - t1 <= 60:
yield (int(f1), int(f2), int(t2 - t1)), int(t1)
index = defaultdict(list)
def add(name, audio):
for h, t in hashes(audio):
index[h].append((name, t))
def name(clip):
votes = Counter()
for h, t in hashes(clip):
for song, at in index.get(h, []):
votes[(song, at - t)] += 1
return votes.most_common(1)[0] if votes else None
def tune(seed, seconds=30):
rng = np.random.default_rng(seed)
note = np.arange(RATE // 4) / RATE
return np.concatenate([sum(np.sin(2 * np.pi * f * note) for f in rng.uniform(200, 3000, 3)) for _ in range(seconds * 4)])
songs = {f"song {i}": tune(i) for i in range(5)}
for title, audio in songs.items():
add(title, audio)
start = 11 * RATE
clip = songs["song 3"][start:start + 6 * RATE] + np.random.default_rng(9).normal(0, 1.0, 6 * RATE)
(match, offset), count = name(clip)[0], name(clip)[1]
print(match, "at about", round(offset * 512 / RATE, 1), "s with", count, "agreeing pairs")
