Getting clean audio from the mic
The tuner asks for the microphone with every voice-call filter switched off. Echo cancellation, noise suppression and automatic gain are tuned for speech, and on a sustained note they pump the level and smear the waveform the detector needs.
navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: false,
noiseSuppression: false,
autoGainControl: false,
},
});The stream goes into an AnalyserNode, and about 30 times a second the tuner copies out the latest block of samples with getFloatTimeDomainData(). The block has to hold at least three periods of the lowest note it looks for, rounded up to a power of two. For the guitar tuner the floor is 55 Hz, which leaves room below drop C, so at 48 kHz that's 4,096 samples, about 85 ms of sound.
Before any maths, a level check throws out blocks quieter than about −50 dBFS RMS. Below that it's room noise, not a string.
Why not just use an FFT?
The first idea most people have is to take a Fourier transform and pick the loudest frequency. It fails on a guitar for two reasons.
The first is resolution. With 4,096 samples at 48 kHz, FFT bins are 11.7 Hz apart. The low E string is 82.41 Hz, and the next semitone up is only about 4.9 Hz away. A tuner has to show a cent, a hundredth of a semitone, which at that pitch is about 0.05 Hz. You can interpolate between bins, but you're starting very coarse.
The second is worse: the loudest frequency often isn't the note. A low string's fundamental is weak next to its harmonics, and small laptop and phone mics roll off the bass on top of that. Here's a synthetic low E built that way, with a quiet fundamental and a strong second harmonic, fed through a windowed FFT:
Your ear still hears E2, because the harmonics are all spaced 82.41 Hz apart and the waveform repeats every 12.13 ms. So instead of asking which frequency is loudest, the tuner asks how often the waveform repeats.
Finding the period: the McLeod pitch method
The detector uses the normalized square difference function (NSDF) from Philip McLeod and Geoff Wyvill's paper A Smarter Way to Find Pitch (International Computer Music Conference, 2005). For each lag, it compares the block with a copy of itself shifted by that many samples:
for (let lag = 0; lag <= maxLag; lag++) {
let acf = 0; // how alike the block and its shifted copy are
let m = 0; // their combined energy
for (let i = 0; i < n - lag; i++) {
const a = buf[i];
const b = buf[i + lag];
acf += a * b;
m += a * a + b * b;
}
nsdf[lag] = m > 0 ? (2 * acf) / m : 0;
}The result is 1 when the block lines up perfectly with its shifted copy, 0 when the two are unrelated, and −1 when they're inverted. Plain autocorrelation (acf alone) sags at longer lags, because fewer samples overlap and the note is dying away. Dividing by the energy m cancels that, so peaks at different lags can be compared fairly, and the height of the chosen peak works as a confidence score. The tuner calls it clarity.
Here's the NSDF of the same synthetic low E:
Picking the right peak
The detector skips the first stretch, where the lag is so small the block still matches itself. After that it takes one peak per positive stretch of the curve.
Picking the highest of those peaks sounds right but causes octave errors in the other direction. A clean note repeats at one period, and also at two and three, and noise can push one of those later peaks a hair above the true one. So the rule is to take the first peak that reaches 90% of the highest:
// One peak per positive stretch after the first zero crossing
// ...collect them into peaks[]...
// The first peak close to the highest one is the period;
// later ones are its multiples
const top = Math.max(...usable.map((p) => nsdf[p]));
const pick = usable.find((p) => nsdf[p] >= top * 0.9)!;In the chart, the bump at lag 292 is far below the dashed 90% line, so it's skipped, and lag 582 is the first peak over it. The next multiple, near lag 1164, falls outside the guitar's search window here, but with a lower floor it would be a second candidate of nearly the same height. Taking the first one is what stops the tuner from reading E1.
Getting finer than one sample
Lags are whole samples, and at these pitches one sample is a big step. At 48 kHz, the low E's period is about 582.5 samples, and moving one sample changes the pitch by 3.0 cents. That's coarser than the in-tune zone.
So the detector fits a parabola through the peak and its two neighbours and takes the top of the parabola as the period:
// Parabola through the peak and its neighbours
const [a, b, c] = [nsdf[pick - 1], nsdf[pick], nsdf[pick + 1]];
const den = a - 2 * b + c;
const shift = den ? (0.5 * (a - c)) / den : 0;
const hz = sampleRate / (pick + shift);On the synthetic low E above, the detector returns 82.411 Hz, 0.02 cents from the 82.41 Hz it was built from, with a clarity of 0.999. A real string in a real room is messier. With a clean pluck, readings hold to about a cent.
Keeping the needle steady
A correct reading for one block isn't enough for a usable needle. Around the detector, the tuner adds a few rules:
- Clarity below 0.85 is ignored. Chords, a string buzzing against a fret and room noise all score low. If nothing clear arrives for 1.2 seconds, the display goes back to waiting.
- The reading is the median of the last five. A median drops the odd bad block where an average would drag the needle toward it. When a new reading lands more than half a semitone from the median, the history starts over, so moving to the next string doesn't blend two notes.
- The needle eases toward the reading. Each update covers 40% of the remaining distance. That's fast enough to follow a turning peg and smooth enough to read.
- "In tune" means within 5 cents for 0.7 seconds. A string passing through on its way up doesn't count.
- The target string is the nearest one, in cents. If a string is so far off that it's closer to its neighbour, the player can lock the tuner to a string by tapping it.
Reaching a bass's low B on a phone
The NSDF compares every sample in the block at every lag, so its cost is block length times lags searched. For the guitar at 48 kHz that's about 3.6 million multiply-adds per block, around 30 times a second. Fine on a laptop, and fine on a phone.
A 5-string bass goes down to B0, 30.87 Hz. With a 28 Hz floor at 48 kHz, the block grows to 8,192 samples and the lag search to 1,715, so one block costs about 14.0 million operations. Thirty times a second is too much for a phone.
A bass doesn't need 48 kHz, though: its fundamentals stop below 400 Hz. So the bass tuner low-passes the input at 1 kHz and averages each group of four samples into one, analysing at 12 kHz. The block and the lag range both shrink by four, so the work drops to about 0.9 million operations, 16 times less.
The low-pass has to come first. Downsampling to 12 kHz folds anything above 6 kHz back into the band as false tones. The tuner chains two Web Audio BiquadFilterNode low-passes (Q 0.707) for a 24 dB per octave slope, which puts 6 kHz about 60 dB down. The parabola step matters even more here: at 12 kHz, one sample at the low B is about 4.4 cents.
What it can't do
- Chords. Several notes don't repeat at one period, so clarity drops and the tuner waits. It's a tuner for one string at a time.
- The first moment of a hard pluck. A string goes slightly sharp at the attack and settles as it rings. The detector reports that honestly, which is why the instructions say to watch the needle once it settles.
- 12-string octave pairs. The thin string of each low pair is an octave up, so the tuner shows it as a different note unless you lock it to that string.
Try it
The guitar tuner has standard and nine alternate tunings, and the bass tuner covers 4, 5 and 6 strings. Both have a reference tone for every string, so they also work by ear without a mic. Nothing you play is recorded or sent anywhere: all of the above runs on your device.