跳到正文
DEV Community· asad·· 2 小時前AI 評分41

如何在瀏覽器中用自相關建立簡易人聲音高追蹤器

Building a Simple Vocal Pitch Tracker in the Browser With Autocorrelation

AI 導讀

文章以不使用程式庫的方式,示範如何在瀏覽器中用 Web Audio API 和自相關建立人聲音高追蹤器,將音高換算為音符名稱及偏差音分。追蹤器適用於 70 至 1000 Hz;對完整混音的讀數容易跳動,使用分離人聲則較穩定。簡單自相關可能把音高判低一個八度,氣聲或耳語則會回傳 null。

正文

asad

Pitch detection is a fun Web Audio project, and it becomes genuinely useful when you pair it with an isolated vocal track: you can see, note by note, whether a singer is sharp or flat. This post builds a small browser pitch tracker using autocorrelation, with no libraries.

Getting audio into an AnalyserNode

You can analyse either the microphone or an audio file. For a file (for example an acapella you exported), an <audio> element works well:

const ctx = new AudioContext();
const audioEl = document.querySelector("audio");
const source = ctx.createMediaElementSource(audioEl);
const analyser = ctx.createAnalyser();
analyser.fftSize = 2048;
source.connect(analyser);
analyser.connect(ctx.destination); // so you still hear it

For the microphone, replace the source with:

const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const source = ctx.createMediaStreamSource(stream);

Autocorrelation in a few lines

Autocorrelation compares a signal with a delayed copy of itself. The delay (lag) at which they match best is one period of the waveform, and the frequency is sampleRate / lag.

function detectPitch(buf, sampleRate) {
  // Ignore near-silence
  let rms = 0;
  for (const v of buf) rms += v * v;
  rms = Math.sqrt(rms / buf.length);
  if (rms < 0.01) return null;

  const minLag = Math.floor(sampleRate / 1000); // 1000 Hz upper limit
  const maxLag = Math.floor(sampleRate / 70);   // 70 Hz lower limit
  let bestLag = -1, best = 0;

  for (let lag = minLag; lag <= maxLag; lag++) {
    let sum = 0;
    for (let i = 0; i < buf.length - lag; i++) sum += buf[i] * buf[i + lag];
    if (sum > best) { best = sum; bestLag = lag; }
  }
  return bestLag > 0 ? sampleRate / bestLag : null;
}

The 70 to 1000 Hz range covers almost all singing voices and keeps the loop short.

Frequency to note name

const NAMES = ["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];

function toNote(freq) {
  const n = 12 * Math.log2(freq / 440) + 69;   // MIDI note number
  const rounded = Math.round(n);
  const cents = Math.round((n - rounded) * 100);
  return { name: NAMES[rounded % 12] + (Math.floor(rounded / 12) - 1), cents };
}

cents tells you how far off the nearest note the voice is: negative is flat, positive is sharp.

The update loop

const buf = new Float32Array(analyser.fftSize);
const out = document.querySelector("#note");

function tick() {
  analyser.getFloatTimeDomainData(buf);
  const f = detectPitch(buf, ctx.sampleRate);
  if (f) {
    const { name, cents } = toNote(f);
    out.textContent = `${name} ${cents >= 0 ? "+" : ""}${cents}c (${f.toFixed(1)} Hz)`;
  }
  requestAnimationFrame(tick);
}
audioEl.addEventListener("play", () => { ctx.resume(); tick(); });

Why an isolated vocal matters

Run this on a full mix and the readout jumps around, because bass, guitars and keys all have their own periods that compete with the voice. On an isolated vocal the result is stable enough to follow a melody. To get one from a song you own, you can use an AI vocal splitter in the browser, then load the vocal stem into the page above.

Limitations

  • Plain autocorrelation sometimes picks an octave too low. Checking whether half the lag also correlates strongly fixes most cases.
  • Breathy or whispered passages have no clear period and return null, which is correct.
  • The nested loop is fine for one voice at 60 fps; for heavier use, move it to an AudioWorklet or use an FFT-based method.

It is a small amount of code for a tool that makes pitch problems very visible, which is exactly what you want when practising.

來源:DEV Community · dev.to