DevTools Logo
All posts

Sample-Accurate Metronome Timing With the Web Audio API

August 28, 2026 · DevTools

metronome
tuner
web-audio
music

A metronome is one of the least forgiving timing problems on the web — human perception notices audio jitter of just a few milliseconds, which rules out setInterval as the direct trigger for each click. The Metronome & Instrument Tuner uses the pattern the Web Audio community settled on years ago: schedule sound events against the AudioContext's own high-precision clock, ahead of time, and use setTimeout only as a coarse loop that keeps refilling the schedule.

Look-ahead scheduling, not just-in-time triggering

Every ~25ms, the scheduler checks whether any beats fall within the next 100ms and, for each one, creates an oscillator whose start() and stop() times are set to the exact future audio-clock time that beat should land on — not "play now." Because the oscillator's timing is handled by the audio hardware's own clock rather than JavaScript's event loop, the click lands sample-accurately regardless of whatever the main thread is doing at that instant. The downbeat of each measure gets a higher-pitched click (1200Hz vs 800Hz) so you can hear where beat one falls without watching the screen.

Tap tempo and beats per measure

Tapping the tempo button repeatedly averages the intervals between taps into a BPM value — useful for matching a metronome to a song you're listening to rather than guessing a number. Beats-per-measure (2 through 6) just changes which beat in the cycle gets the accented click.

The tuner: autocorrelation, not FFT peak-picking

Pitch detection here uses time-domain autocorrelation — sliding a copy of the captured waveform against itself across a range of lags and finding the lag with the strongest self-correlation, which corresponds to the fundamental period. That's more robust for a single sustained note than picking the loudest FFT bin, which can lock onto a harmonic instead of the fundamental. The detected frequency converts to a note name and a cents-offset from true pitch against an adjustable A4 reference (440Hz by default, but tunable for orchestras that tune sharp).

Pairing it with other audio tools

The tuner needs a quiet room to lock onto pitch reliably — check ambient noise first with the Sound & Decibel Meter. For keeping steady time on something other than music, like an exam or a workout interval, the Precision Stopwatch uses a different but equally drift-resistant timing approach.

Tools mentioned in this post