How Instrument Tuners Actually Work: Pitch Detection Explained

Point a microphone at a guitar string and a browser tab can tell you, within a few milliseconds, exactly how many cents sharp or flat it is. No plugin, no upload, no round trip to a server — just a few hundred lines of math running on the same audio buffer your browser already has in memory. Here's what's actually happening underneath.

The problem: finding a fundamental frequency

A plucked string doesn't produce one clean sine wave; it produces a fundamental frequency plus a stack of quieter harmonics on top, all summed into one messy waveform. Pitch detection means recovering that one fundamental frequency — the number that determines what note you hear — from the combined signal.

Why autocorrelation works

Autocorrelation is a simple idea: take a chunk of the audio buffer, and compare it against a copy of itself shifted forward in time by some small delay. If the underlying wave is periodic — which a sustained musical note is — then at exactly one delay (the wave's period) the shifted copy lines up almost perfectly with the original, and the sum of the products spikes. Sweep the delay across a range of plausible values, find where that sum peaks, and you've found the period. Frequency is just the sample rate divided by that period in samples.

perfecttune.net's Tuner does exactly this: it grabs a 2048-sample window from a Web Audio AnalyserNode, computes the autocorrelation across a range of lags, and picks the lag with the strongest correlation (after skipping the initial, always-strong zero-lag peak). A parabolic interpolation around that best lag refines the result to sub-sample precision, which is the difference between a needle that visibly jitters and one that sits still.

From frequency to note name

Once you have a frequency in Hz, converting it to a note name is pure equal-temperament math. Every note's frequency is a fixed ratio away from a reference pitch — conventionally A4 at 440 Hz — specifically 440 × 2^((n-69)/12) where n is the note's MIDI number. Run that formula backward on a detected frequency, round to the nearest whole MIDI number, and you get the nearest note; the leftover fractional distance, converted to cents (1/100th of a semitone), is exactly the needle reading.

Why it has to run in the browser

A tuner needs to update dozens of times per second to feel responsive, and every one of those updates depends on raw, continuous microphone audio. Uploading that audio to a server for analysis would mean latency, bandwidth, and — far more importantly — sending a live mic feed off your device for no real benefit, since a modern browser's JavaScript engine can run this entire pipeline, autocorrelation and all, comfortably in real time on ordinary hardware. Keeping it local isn't a compromise; it's strictly the better design.

← Back to perfecttune.net