惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Full Disclosure
Latest news
Latest news
P
Privacy International News Feed
T
Tenable Blog
Schneier on Security
Schneier on Security
O
OpenAI News
K
Kaspersky official blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
C
Cisco Blogs
L
LangChain Blog
H
Help Net Security
W
WeLiveSecurity
V
Vulnerabilities – Threatpost
C
Cyber Attacks, Cyber Crime and Cyber Security
AWS News Blog
AWS News Blog
博客园 - 叶小钗
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
罗磊的独立博客
C
Check Point Blog
Engineering at Meta
Engineering at Meta
J
Java Code Geeks
Stack Overflow Blog
Stack Overflow Blog
雷峰网
雷峰网
MongoDB | Blog
MongoDB | Blog
C
Cybersecurity and Infrastructure Security Agency CISA
P
Privacy & Cybersecurity Law Blog
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 【当耐特】
V2EX - 技术
V2EX - 技术
Spread Privacy
Spread Privacy
博客园 - Franky
T
Threatpost
T
Tor Project blog
P
Proofpoint News Feed
D
DataBreaches.Net
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
H
Heimdal Security Blog
NISL@THU
NISL@THU
大猫的无限游戏
大猫的无限游戏
Microsoft Security Blog
Microsoft Security Blog
Know Your Adversary
Know Your Adversary
I
Intezer
T
Tailwind CSS Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
美团技术团队
博客园 - 聂微东
T
Threat Research - Cisco Blogs
PCI Perspectives
PCI Perspectives
The Hacker News
The Hacker News
B
Blog RSS Feed

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Why Your Web Audio Tuner Sucks at Low Notes (and What to Use Instead of FFT)
SEN LLC · 2026-04-25 · via DEV Community

The first thing anyone reaches for when building a pitch detector in the browser is AnalyserNode.getFloatFrequencyData() — the FFT magnitude spectrum. It works, and then it fails the instant you plug in a guitar and play the low E. Here's why, and what to do about it.

Sub-cent-accurate tuning from ~80 lines of autocorrelation. No dependencies. Plain JS.

pitch-detector UI in guitar-tuner mode, showing A detected at 111.50 Hz, +23 cents sharp of the A2 target string, with a live waveform below. Dark theme.

🎙 Demo: https://sen.ltd/portfolio/pitch-detector/
📦 GitHub: https://github.com/sen-ltd/pitch-detector

The symptom — FFT-based tuners can't read low notes

The canonical Web Audio pitch detector looks like this:

const ctx = new AudioContext();           // default sampleRate = 48000
const analyser = ctx.createAnalyser();
analyser.fftSize = 2048;                  // the default
const spectrum = new Float32Array(analyser.frequencyBinCount);

requestAnimationFrame(function loop() {
  analyser.getFloatFrequencyData(spectrum);
  const maxBin = argmax(spectrum);
  const freq = maxBin * ctx.sampleRate / analyser.fftSize;
  // turn freq into a note name…
  requestAnimationFrame(loop);
});

Enter fullscreen mode Exit fullscreen mode

Play an A4 (440 Hz) and it lights up around 440. Perfect. Then play the low E on a guitar (E2 = 82.41 Hz) and the readout jumps between "82 Hz" and "105 Hz" like a broken cursor. The reason is bin width:

bin width = sampleRate / fftSize = 48000 / 2048 = 23.4375 Hz

Enter fullscreen mode Exit fullscreen mode

And the distance between semitones scales with frequency, so low notes are closer together:

Note Frequency Distance to next semitone
E2 82.41 Hz 4.90 Hz (to F2)
A2 110.00 Hz 6.54 Hz
A4 440.00 Hz 26.16 Hz
A5 880.00 Hz 52.33 Hz

E2 and F2 are less than one-fifth of a bin apart. The FFT literally cannot tell them apart. That "I tuned my guitar and it sounded wrong" feeling? That was your tuner.

The workarounds and their limits

  • Crank up fftSize: 32768 gets bin width down to 1.46 Hz, but fftSize >= 2 * N, so you need 32768 samples (~0.68 s at 48 kHz) of latency and memory per frame. Rough for a live display.
  • Zero padding: increases resolution in appearance only. You're not measuring anything more; you're interpolating.
  • Parabolic interpolation: fit a quadratic to the three bins around the peak and estimate the apex. Classic trick, gets you closer, but doesn't help if two peaks are blurred into one.

And there's a deeper problem.

Pitch is not frequency

An A4 isn't pure; it contains partials at 880, 1320, 1760 Hz and up. In an FFT magnitude spectrum, depending on the instrument and the moment of the recording, the second harmonic can be louder than the fundamental. Plucked guitar, right after the pick attack, is a famous case. Naïve argmax returns 880 Hz — A5, an octave off.

You can patch around this (HPS = Harmonic Product Spectrum, or peak-picking with harmonic constraints) but none of these patches are about pitch, they're about cleaning up the mess that FFT handed you. And they don't fix the bin-width problem.

The physical definition of pitch is the period at which the waveform repeats. If a signal repeats every 480 samples at 48 kHz, that's a 100 Hz pitch. Harmonics don't change the period — they change the shape of each cycle. So measure the period directly.

Autocorrelation — measuring the period directly

The autocorrelation function (ACF) is the buffer's inner product with a copy of itself shifted by τ samples:

r[τ] = Σ_{i=0..N−τ−1} buffer[i] · buffer[i + τ]

Enter fullscreen mode Exit fullscreen mode

  • At τ = 0, every term is buffer[i]², so r[0] is the max (signal energy).
  • When τ hits one period, the shifted copy lines up with itself again and r[τ] peaks.
  • The location of the first prominent peak is the period.

Frequency = sampleRate / τ. That's the whole idea.

export function detectPitch(buffer, sampleRate) {
  const N = buffer.length;
  const minLag = Math.floor(sampleRate / 1500); // upper freq bound 1500 Hz
  const maxLag = Math.floor(sampleRate / 60);   // lower freq bound 60 Hz

  // RMS gate — don't run on silence
  let sumSq = 0;
  for (let i = 0; i < N; i++) sumSq += buffer[i] * buffer[i];
  if (Math.sqrt(sumSq / N) < 0.01) return null;

  const r0 = acf(buffer, 0, N);

  // Skip past the initial descent from r[0]
  let lag = minLag;
  while (lag < maxLag && acf(buffer, lag, N) > acf(buffer, lag + 1, N)) lag++;

  // Find the highest local maximum in the remaining range
  let bestLag = -1, bestVal = -Infinity;
  while (lag < maxLag - 1) {
    const a = acf(buffer, lag - 1, N);
    const b = acf(buffer, lag, N);
    const c = acf(buffer, lag + 1, N);
    if (b > a && b >= c && b > bestVal) { bestVal = b; bestLag = lag; }
    lag++;
  }
  if (bestLag < 0 || bestVal / r0 < 0.5) return null;  // reject weak periodicity

  // Parabolic interpolation for sub-sample precision
  const a = acf(buffer, bestLag - 1, N);
  const b = bestVal;
  const c = acf(buffer, bestLag + 1, N);
  const shift = (a - c) / (2 * (a - 2*b + c));
  return sampleRate / (bestLag + shift);
}

function acf(buf, lag, N) {
  let s = 0;
  for (let i = 0; i < N - lag; i++) s += buf[i] * buf[i + lag];
  return s;
}

Enter fullscreen mode Exit fullscreen mode

Three things matter:

1. Choose maxLag from your lower frequency bound. A lower limit of 60 Hz means maxLag = 800 samples at 48 kHz. You want at least two periods inside the buffer, so maxLag ≤ N / 2 is the practical cap. Pushing too low starves the estimator.

2. Skip the initial descent. r[τ] is a plateau around τ = 0, then dips, then rises back at the period. Walk forward until the values stop decreasing before you start peak-hunting — otherwise you'll pick τ = 1 and report 48 kHz.

3. Reject weak peaks by ratio to r[0]. Noise doesn't have a clean period, so it doesn't produce a sharp peak. bestVal / r0 < 0.5 says "we don't have a confident period" and returns null. This is what lets the tuner stay quiet on background hiss instead of guessing wildly.

Parabolic interpolation for sub-sample precision

Integer lags are discrete, so raw ACF gives you integer-sample period resolution. For A4 (440 Hz, period ≈ 109 samples) one sample off is 48000/109 - 48000/110 = 4 Hz, about 15 cents. Not good enough.

Fit a parabola through (bestLag-1, bestLag, bestLag+1) and solve for the apex. Standard trick, ~4 lines of code, and the tests show it nails pure sines to under 1 cent.

test("detects 440 Hz sine within 1 cent", () => {
  const buf = sineBuffer(440, 0.04);   // 40 ms ≈ 1920 samples
  const f = detectPitch(buf, 48000);
  const cents = 1200 * Math.log2(f / 440);
  assert.ok(Math.abs(cents) < 1);
});

Enter fullscreen mode Exit fullscreen mode

Wiring it to Web Audio

You want the time-domain buffer, not the FFT. AnalyserNode.getFloatTimeDomainData() hands back a Float32Array of raw samples, exactly what detectPitch consumes.

const stream = await navigator.mediaDevices.getUserMedia({
  audio: { echoCancellation: false, noiseSuppression: false, autoGainControl: false },
});
const ctx = new AudioContext();
const src = ctx.createMediaStreamSource(stream);
const analyser = ctx.createAnalyser();
analyser.fftSize = 2048;
src.connect(analyser);

const buf = new Float32Array(analyser.fftSize);
requestAnimationFrame(function loop() {
  analyser.getFloatTimeDomainData(buf);
  const f = detectPitch(buf, ctx.sampleRate);
  if (f) render(f);
  requestAnimationFrame(loop);
});

Enter fullscreen mode Exit fullscreen mode

Gotcha: echoCancellation, noiseSuppression, and autoGainControl default to true. All three assume "human voice making words" and actively fight pure tones — they'll gate out your test sine wave entirely. Set them to false for any musical application.

Smooth in log-frequency space, not Hz

The readout will wobble if you display raw per-frame estimates, so you'll reach for exponential smoothing. Important: do it in log₂(Hz), not linear Hz. Human pitch perception is logarithmic — a 2 Hz wobble at A2 is a very different problem from a 2 Hz wobble at A5.

const alpha = 0.35;
const sLog = Math.log2(smoothedFreq);
const fLog = Math.log2(newFreq);
smoothedFreq = Math.pow(2, sLog * (1 - alpha) + fLog * alpha);

Enter fullscreen mode Exit fullscreen mode

Result: identical responsiveness and stability across the instrument's range.

Cost vs. the alternative

ACF is O(N · L) where L is the candidate lag range. For N = 2048 and L ≈ 768 that's ~1.5M multiply-adds per frame. On a laptop Chrome this runs in well under 1 ms — negligible inside a 16.7 ms animation frame.

FFT is O(N log N), about 60× cheaper in theory. But when your ACF frame is already sub-millisecond, the win isn't compelling enough to give up the low-note accuracy.

For larger buffers, polyphonic input, or heavier denoising, look at YIN (a refined ACF variant) or CREPE (a small neural net). But for a monophonic tuner, plain autocorrelation is enough, and it fits in 80 lines.

The takeaway

  • FFT tuners fail at low frequencies because the bin width (sampleRate / fftSize ≈ 23 Hz) is larger than the semitone spacing at E2 (4.9 Hz).
  • Pitch is the period at which the waveform repeats. Measure it directly with autocorrelation.
  • Three things make the algorithm robust: skip the initial descent, threshold the peak-to-energy ratio for noise rejection, and parabolic-interpolate the peak for sub-sample precision.
  • Web Audio integration caveats: use getFloatTimeDomainData(), disable the voice-assistant effects on the getUserMedia constraints, smooth in log space.

Full source on GitHubdetector.js is the algorithm, tests/detector.test.js is 14 tests covering sines, sawtooths, silence, noise, and all the tuner presets. MIT licensed.

Live demo — allow mic access and sing, whistle, or play an instrument at it.