DEV Community

Caron
Caron

Posted on

Real-time pitch detection in the browser — how it works and a free tool to try it

Ever wondered how a tuner app knows what note you're playing? The underlying tech
is surprisingly accessible in modern browsers — no native app, no plugins required.

How browser-based pitch detection works

Modern browsers expose the Web Audio API, which gives you access to the
microphone via getUserMedia(). Once you have an audio stream, you can run
pitch detection algorithms on the raw frequency data.

The most common approaches:

1. FFT (Fast Fourier Transform)
The Web Audio API's AnalyserNode can compute an FFT of the input signal,
giving you a frequency spectrum. The dominant frequency peak is your pitch —
but this can be noisy with real instruments.

2. Autocorrelation
More robust for musical instruments. You compare the audio signal against
a time-shifted version of itself. The lag at which they correlate best
reveals the fundamental frequency.

3. YIN algorithm
A refinement of autocorrelation that reduces octave errors. Popular in
professional pitch detection tools.

From Hz to note name

Once you have a frequency in Hz, mapping it to a note is just math:


`js
function freqToNote(freq) {
  const noteNum = 12 * (Math.log(freq / 440) / Math.log(2));
  return Math.round(noteNum) + 69; // MIDI note number
}

const noteNames = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B'];
function midiToName(midi) {
  return noteNames[midi % 12] + Math.floor(midi / 12 - 1);
}`
Enter fullscreen mode Exit fullscreen mode

Top comments (0)