Tuning Browser Pitch Detection (YIN) to Within 0.6% of Praat on Real Speech
TL;DR: Pure JavaScript pitch detection often looks accurate on sine waves and falls apart on real speech. When I benchmarked my browser YIN implementation against Praat across 80 LibriSpeech recordings, an 85 ms window missed Praat's median by 3.2% typically and up to 18%. Switching to a 32 ms window, adding two-threshold voicing hysteresis, and using a relative silence gate brought typical difference down to 0.6% (71 of 80 within 2%)—with zero audio ever leaving the browser.
Why run speech pitch detection purely in the browser?
People measure their speaking pitch for singing practice, curiosity, or gender-affirming voice training. Voice recordings in those contexts are personal. Sending raw microphone audio to a backend API adds privacy risk, server costs, and latency for a computation a phone browser can run locally.
When I built Vocal Analyzer, I made the site pure static files with no server code that could receive audio. Anyone can open their browser's developer tools Network tab while recording and verify that no request carries audio.
That architectural choice sounds simple until you try to match desktop phonetic tools like Praat in JavaScript. Synthetic test tones from 82 Hz to 1,047 Hz passed within 1% on day one. Real human speech did not.
Web Audio microphone pitfalls before you even run YIN
Before tuning pitch math, four browser audio quirks quietly distorted the input signal.
1. Browser voice processing reshapes pitch and amplitude. By default, getUserMedia enables echo cancellation, noise suppression, and automatic gain control. Automatic gain control pulls a sustained note down while a user holds it, and noise suppression eats quiet phrase endings. Disabling all three keeps the raw signal intact:
const stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: false, noiseSuppression: false, autoGainControl: false, }, }); 2. Stereo averaging halves your signal on some microphones. Once echo cancellation is off, some browsers deliver a stereo stream where one channel is completely silent. Averaging channels halves the input level. Inside the AudioWorkletProcessor, I compute block energy per channel and keep the loudest channel for each 1024-sample block instead of averaging.
3. Timers drop frames in throttled tabs. Polling an AnalyserNode with setInterval drifts whenever the browser throttles timers. Driving analysis directly from incoming audio hops (every 16 ms of audio) keeps frame timing consistent.
4. Integer box-filter decimation drifts across 44.1 kHz and 48 kHz devices. YIN's difference function scales as O(window * maxLag). Running at 48 kHz costs 9x the CPU of 16 kHz even though voice F0 stays well below 1.1 kHz.
My first shortcut used a box filter dividing by round(sampleRate / 16000). On a 44.1 kHz laptop, that gave 14.7 kHz instead of 16 kHz—aliasing high frequencies and changing the effective window length between devices. Replacing it with a 31-tap Hamming-windowed sinc low-pass at 7 kHz plus linear resampling to exact 16 kHz made results nearly identical across sample rates:
- 16 kHz input: 0.64% typical median diff, 5.6% worst
- 44.1 kHz input: 0.61% typical median diff, 5.3% worst (previously 0.71% / 6.5% with the box filter)
- 48 kHz input: 0.59% typical median diff, 5.4% worst
Benchmarking browser pitch detection against Praat
To stop guessing, I wrote a reproducible benchmark script (scripts/f0-eval/) using 80 read-aloud recordings from LibriSpeech dev-clean (40 adult speakers, 20 male and 20 female, longest two clips per speaker). I generated reference pitch tracks with Praat's to_pitch via praat-parselmouth (16 ms hop, 60–500 Hz) and ran the exact browser trackSamples function on the same audio.
The first implementation used an 85 ms window—chosen intuitively to fit plenty of low-frequency cycles—and a standard YIN threshold of 0.15 (from de Cheveigné & Kawahara, 2002).
The 85 ms baseline failed badly on real speech:
- Typical median difference vs. Praat: 3.2%
- Worst recording: 18%
- Recordings within 5% of Praat: only 52 of 80
Looking at the dropped frames showed why. Speech pitch moves continuously, especially on falling phrase endings. An 85 ms window spans too much pitch movement, smears periodicity inside the window, and causes YIN to drop those lower trailing frames. Dropping low phrase endings biased the whole-recording median upward.
My first instinct was wrong: raising the global YIN threshold from 0.15 to 0.35 lowered median difference from 3.2% to 2.3%, but gross frame errors (>20% off) jumped from 1.8% to 6.2% from octave slips. Changing the RMS silence floor from 0.01 to 0.001 had almost no effect.
What worked: 32 ms windows, voicing hysteresis, and a relative gate
Three small changes fixed the problem without blowing up gross errors.
1. Shrink the window from 85 ms to 32 ms (512 samples at 16 kHz). Sweeping shorter windows showed 32 ms was the sweet spot. Shorter windows track moving phrase endings without smearing periodicity. Typical median difference dropped immediately from 3.2% to 1.07%, worst-case error fell from 18% to 9.7%, and gross errors stayed flat at 2.0%.
The tradeoff is clean and predictable: YIN's longest lag is half the window (256 samples at 16 kHz), which sets a hard pitch floor of 62.5 Hz—below C2 and normal speaking voices, though it skips vocal fry.
2. Add two-threshold voicing hysteresis (linkVoicing). Instead of raising the YIN threshold everywhere, the detector computes the YIN difference function once per frame and reads it at two thresholds: strict (0.15) and loose (0.4). A loose-only frame is accepted only if it neighbours an already voiced frame within 150 cents, scanning forward and backward across the take:
export function linkVoicing( strict: (number | null)[], loose: (number | null)[], linkCents = 150, ): (number | null)[] { const out = [...strict]; for (let k = 1; k < out.length; k++) if (out[k] == null && loose[k] != null && out[k - 1] != null && cents(loose[k]!, out[k - 1]!) <= linkCents) out[k] = loose[k]!; for (let k = out.length - 2; k >= 0; k--) if (out[k] == null && loose[k] != null && out[k + 1] != null && cents(loose[k]!, out[k + 1]!) <= linkCents) out[k] = loose[k]!; return out; } This recovers weak, falling phrase endings while rejecting isolated octave slips. On the live microphone path, the same rule runs causally (a loose frame only links to the previous voiced frame), followed by a causal median of the last 5 voiced values. Once recording stops, the speech tools re-run trackSamples on the in-memory recording so live results match uploaded files.
3. Use a relative silence gate. A fixed RMS cutoff either drops quiet phone mics or passes room hiss on loud recordings. Setting the gate to max(0.002, 0.03 * peakRms) adapts automatically to input level. Sweeping 0.01 pushed the worst file up to 9.5%, while 0.1 pushed typical error up to 1.4%.
Here is how each step changed performance across the 80 LibriSpeech recordings:
| Configuration | Typical median diff | Worst file | Within 2% | Within 5% | Gross error (>20%) |
|---|---|---|---|---|---|
| 85 ms baseline (threshold 0.15) | 3.2% | 18% | — | 52 / 80 | 1.8% |
| 85 ms + loose threshold (0.35) | 2.3% | — | — | — | 6.2% (rejected) |
| 32 ms window (512 samples) | 1.07% | 9.7% | 57 / 80 | — | 2.0% |
| 32 ms + hysteresis + relative gate | 0.6% (0.64%) | 5.6% | 71 / 80 | 78 / 80 | 1.8% (1.78%) |
On shared voiced frames, median frame difference is 0.3%. Systematic upward bias disappeared (42 files slightly above Praat, 38 slightly below; signed bias moved from +0.9% to +0.1%). False voicing on white noise and brown noise is 0%.
Knowing when to stop: checking a second reference (pYIN)
Praat is a widely used reference, not absolute ground truth. Before chasing that single 5.6% worst-case file down below 5%, I ran librosa 0.11's pYIN (60–500 Hz, frame 1024, hop 256) on the exact same 80 recordings.
- My detector vs. pYIN: 1.3% typical median difference (55 of 80 within 2%).
- Praat vs. pYIN against each other: 1.0% typical median difference, up to 7.9% maximum.
- The single worst recording against Praat (5.6%) differed from pYIN by only 0.5%.
That was the signal to stop tuning. Trying to force that worst file below 5% against Praat would have meant overfitting to one reference implementation well below the disagreement between Praat and pYIN themselves. Synthetic voice-like test tones (82 Hz to 1,047 Hz, including added noise) still run on every code change to enforce < 1% accuracy against known ground truth.
Honest limitations and when not to use this
Client-side YIN has real limits you should document clearly if you ship it to users:
- Pitch floor around 62.5 Hz: Vocal fry and very low irregular phonation often sit below this floor and are not measured.
- Noisy rooms and Bluetooth mics: Background noise, very breathy or creaky voice, and Bluetooth headset microphones in call mode add error. Silence, breath, and unvoiced consonants like
sandfare skipped, and a reliable speech summary needs at least 3 seconds of voiced sound (20–30 seconds of reading gives a steadier median). - Browser test coverage: So far, the tools have been tested in desktop Chrome (including the fallback path older browsers use). Mobile Safari and diverse Android audio stacks can still behave differently.
- No accounts or cloud sync: Keeping everything static and local means training history lives only in one browser's local storage (with CSV export and import) and does not sync across devices.
- Pitch is not gender: Listeners perceive voice gender from both fundamental frequency and vocal-tract formant resonance (Hillenbrand & Clark, 2009), and the 155–185 Hz overlap band is a voice-training convention rather than a measured boundary. That is why Vocal Analyzer only reports measured numbers and range context—never a male/female verdict—and explicitly notes it is built by an independent developer, not a clinician, and is not medical advice.
Takeaways
If you are building browser pitch detection for speech today:
- Benchmark on real read speech, not just sine waves. Synthetic tones won't catch phrase-ending smear or voicing bias.
- Disable browser mic processing (
AEC,NS,AGC) and avoid averaging stereo channels blindly inside yourAudioWorklet. - Resample cleanly to 16 kHz with a low-pass filter so a 32 ms window means 32 ms on both 44.1 kHz and 48 kHz hardware.
- Prefer voicing hysteresis over a looser global threshold. Linking strict seeds to nearby loose frames recovers falling phrase endings without letting in octave jumps.
- Compare against two reference trackers (e.g., Praat and pYIN). Once your residuals sit inside the disagreement between references, stop tuning.
This article was created with the help of AI.