DEV Community

Uchit Chakma
Uchit Chakma

Posted on Originally published at ucdreams.com

Building a Zero-Latency In-Browser Guitar Tuner with Web Audio API & YIN Pitch Detection

Building a Zero-Latency In-Browser Guitar Tuner with Web Audio API & YIN Pitch Detection

Most online instrument tuners either require installing a native mobile app or suffer from sluggish pitch tracking, jittery needle physics, and intrusive ad overlays. At UCDREAMS, we engineered a 100% client-side Free Online Guitar Tuner that runs sub-cent pitch detection directly inside the browser using the Web Audio API and an autocorrelation / YIN fundamental frequency estimator.

Everything executes locally in browser memory — zero audio streams are ever sent to a server.


1. Why FFT Peak Picking Fails for Guitar Strings

A classic mistake when building a browser tuner is relying on AnalyserNode.getByteFrequencyData() (a standard Fast Fourier Transform) and picking the loudest frequency bin.

Why does FFT peak-picking fail on acoustic and electric guitars?

  1. Missing Fundamental & Strong Harmonics: Plucking a low E2 string (82.41 Hz) often produces stronger energy at the 2nd (164.8 Hz) or 3rd (247.2 Hz) harmonic than at the fundamental frequency.
  2. Poor Low-Frequency Resolution: At 48,000 Hz sample rate with a 2048-sample FFT, each bin spans 23.4 Hz — far too coarse to distinguish E2 (82.41 Hz) from F2 (87.31 Hz) within +/-1 cent.

Time-domain Autocorrelation / YIN Difference Function solves both problems by finding the exact waveform period in fractional samples.


2. Capturing Raw PCM Audio with Low-Latency Constraints

Disable browser echo cancellation, noise suppression, and auto-gain control when requesting microphone access so harmonic transients are preserved:

const stream = await navigator.mediaDevices.getUserMedia({
  audio: {
    echoCancellation: false,
    noiseSuppression: false,
    autoGainControl: false
  }
});

const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const source = audioCtx.createMediaStreamSource(stream);
const analyser = audioCtx.createAnalyser();
analyser.fftSize = 4096;
source.connect(analyser);

const timeBuffer = new Float32Array(analyser.fftSize);
Enter fullscreen mode Exit fullscreen mode

3. Time-Domain Pitch Detection + Parabolic Interpolation

To achieve sub-cent accuracy (< 0.5 cents) without increasing buffer lag, compute the normalized squared difference across candidate lag periods tau, pick the first dip below threshold 0.15, and refine the minimum with parabolic interpolation:

function detectPitchYIN(buffer, sampleRate, threshold = 0.15) {
  const halfLen = Math.floor(buffer.length / 2);
  const diff = new Float32Array(halfLen);

  // 1. RMS Silence Gate (ignore ambient room noise)
  let rms = 0;
  for (let i = 0; i < buffer.length; i++) rms += buffer[i] * buffer[i];
  if (Math.sqrt(rms / buffer.length) < 0.01) return -1;

  // 2. Squared difference function
  for (let tau = 0; tau < halfLen; tau++) {
    let sum = 0;
    for (let i = 0; i < halfLen; i++) {
      const delta = buffer[i] - buffer[i + tau];
      sum += delta * delta;
    }
    diff[tau] = sum;
  }

  // 3. Cumulative mean normalized difference
  const cmnd = new Float32Array(halfLen);
  cmnd[0] = 1;
  let runningSum = 0;
  for (let tau = 1; tau < halfLen; tau++) {
    runningSum += diff[tau];
    cmnd[tau] = diff[tau] * tau / runningSum;
  }

  // 4. First local minimum below threshold
  let tauEstimate = -1;
  for (let tau = 2; tau < halfLen - 1; tau++) {
    if (cmnd[tau] < threshold) {
      while (tau + 1 < halfLen && cmnd[tau + 1] < cmnd[tau]) tau++;
      tauEstimate = tau;
      break;
    }
  }
  if (tauEstimate === -1) return -1;

  // 5. Parabolic interpolation for fractional sample precision
  const prev = cmnd[tauEstimate - 1];
  const curr = cmnd[tauEstimate];
  const next = cmnd[tauEstimate + 1];
  const shift = (next - prev) / (2 * (2 * curr - next - prev));
  return sampleRate / (tauEstimate + (Number.isFinite(shift) ? shift : 0));
}
Enter fullscreen mode Exit fullscreen mode

Converting Hz to Musical Note & Cents Offset

const NOTE_NAMES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];

function freqToNoteCents(freq, a4 = 440) {
  const midiFloat = 69 + 12 * Math.log2(freq / a4);
  const midi = Math.round(midiFloat);
  const cents = Math.round((midiFloat - midi) * 100);
  const note = NOTE_NAMES[((midi % 12) + 12) % 12];
  const octave = Math.floor(midi / 12) - 1;
  return { note: `${note}${octave}`, cents, freq: Number(freq.toFixed(2)) };
}
Enter fullscreen mode Exit fullscreen mode

4. Try the Live In-Browser Guitar Tuner & Companion Audio Tools

You can test this engine live with real-time microphone detection and reference string tones (Standard, Drop D, Bass, Ukulele):

Explore all 30+ zero-server browser utilities on UCDREAMS Tools Hub, or unwind with our 60FPS real-time multiplayer arcade at UCDREAMS Games.


Need a custom tool, web app, or 95+ PageSpeed site? Built by *UCDREAMS Senior Engineers. Explore our **Custom Website Development, Web App Development, and AI Automation Services.*

Top comments (0)