Why this exists

I run, and I got tired of hunting for playlists that already sit at 180 steps per minute. So I built a small web tool that takes a song you own, detects its tempo, and stretches or shrinks it to any target BPM — entirely in the browser. No upload, no account, no app.

The running angle is just the motivation. The interesting part is that all of the audio processing is hand-rolled DSP in plain JavaScript: beat detection, phase-correct time-stretching, and MP3 encoding, with no WebAssembly, no AudioWorklet, no OfflineAudioContext, and no backend.

The constraint that shaped everything

Most browser audio tools reach for WASM (often a compiled C library like SoundTouch or Rubber Band) or push the heavy work into an AudioWorklet thread. I deliberately avoided both:

  • Zero native code. The DSP is a few hundred lines over Float32Array. It ships as a static site that any dumb file host can serve, and there is nothing to compile.
  • No backend. Files never leave the tab. "No upload" is a real privacy property here, not a marketing line.
  • No AudioWorklet. Keeping it single-threaded and synchronous makes the code trivial to reason about and to unit-test in Node. The cost is that big files block the main thread for a moment — which I mitigate by yielding during encode (below).

Decode is the one piece I lean on the platform for: AudioContext.decodeAudioData turns the uploaded file into an AudioBuffer, which I immediately downmix to mono and resample to 44.1 kHz. The whole pipeline is:

decodeAudioData → toMono → resample(44.1k) → detectBPM → stretchOLA → mixDrums → encodeMp3

Part 1 — Detecting the tempo

Tempo detection has the most entertaining failure modes. The naive version is: compute an onset envelope, autocorrelate it, take the highest-scoring lag, convert to BPM. That gives you 52 BPM when the song is actually 156, because hi-hats on the sixteenth-note grid look more periodic than the downbeats. Here is the pipeline that survives real music.

Energy envelope and onset strength

Split the mono signal into fixed windows of 192 samples (~4.3 ms at 44.1 kHz) and take the RMS of each — a cheap energy envelope:

const W = 192;
const env = new Float32Array(nWin);
for (let i = 0; i < nWin; i++) {
  let s = 0;
  for (let j = 0; j < W; j++) { const v = samples[i * W + j]; s += v * v; }
  env[i] = Math.sqrt(s / W);
}

The "onset strength" is the positive part of the difference between consecutive windows, with the mean subtracted so silent stretches don't dominate:

for (let i = 1; i < nWin; i++) raw[i] = Math.max(0, env[i] - env[i - 1]);

Then a 3-point smoothing pass (0.25·a + 0.5·b + 0.25·c − mean). This deliberately widens the onset peaks. The reason is subtle: autocorrelation is evaluated at integer lags, so a sharp spike that lands between two lags gets split across both and loses the octave contest to a spurious sub-multiple. Smoothing biases the peak toward a single lag.

Autocorrelation with comb weighting

Autocorrelation is scored only over the lag range that maps to 35–240 BPM. The trick that resolves most octave errors is comb-filter weighting: score a lag together with its 2× and 3× harmonics, not alone:

for (let lag = minLag; lag <= maxLag; lag++) {
  let sc = ac[lag];
  if (lag * 2 <= maxLag) sc += 0.5 * ac[lag * 2];
  if (lag * 3 <= maxLag) sc += 0.25 * ac[lag * 3];
  if (sc > bestScore) { bestScore = sc; best = lag; }
}

If the true pulse is at lag L, its energy also shows up strongly at 2L and 3L, so summing the family across the harmonic series beats any single subdivision peak.

Subdivision folding

Comb weighting catches most cases, but when autocorrelation locks onto the fast grid (it reports 155 BPM) and the true tempo is a slow third of that — a 52 BPM R&B track with hats at 156 — you still fold back down. Rule: if the locked value is above 145 BPM and the slow 2× or 3× lag still carries a strong peak, fold:

if ((60 * envRate) / best > 145) {
  if      (tryFold(3, 48, 0.35)) fold = 3;   // slow grid still strong → real pulse is 1/3
  else if (tryFold(2, 70, 0.40)) fold = 2;   // or 1/2
}
best *= fold;

tryFold(k, minBpm, ratio) checks that the slower lag best * k is itself a plausible tempo and that its autocorrelation is at least ratio of the fast peak. This is exactly what DJ software does when it reads a 155-BPM track as 52.

Peak refinement and clamping

When no folding happened, a parabolic interpolation around the integer peak recovers fractional-BPM precision. Finally the result is folded into the 40–240 BPM band and rounded.

The honest limitation: this is an energy/envelope method, not a transient-model one. It is robust on four-on-the-floor and most pop, but a rubato classical passage or atonal material gets a confident-but-wrong number. For a "match my footstrikes" tool that is acceptable — the user can nudge the target — but I don't claim it is reference-grade.

Part 2 — Stretching without detuning (WSOLA)

Once you know the ratio (target BPM ÷ source BPM), you must change duration without sliding the pitch. AudioBufferSourceNode.playbackRate does the opposite: it resamples, dragging the pitch up when you speed up, so vocals go chipmunky.

The classic fix is a phase-vocoder or WSOLA. I implemented the simpler one — WSOLA (Waveform Similarity Overlap-Add) — because it needs no FFT and stays inside plain array math.

The idea

Plain OLA chops the signal into overlapping frames at a fixed synthesis hop and re-adds them at a different rate. That changes duration, but because adjacent frames are taken at arbitrary phase, you get amplitude ripple and a buzzing artifact — waveform discontinuities between frames. WSOLA fixes this by searching, around the ideal analysis position, for the frame whose beginning best matches the tail of the frame you just wrote. You glue similar waveforms together instead of arbitrary ones.

The implementation

const Hs = 512, frame = Hs * 2;
const Ha = Math.max(1, Math.round(Hs / ratio));  // ideal analysis hop
const tol = 256;                                 // similarity search radius (~5.8 ms)
let prevTail = null;
while (op + frame <= outLen && ip + frame + tol < input.length) {
  let k = 0;
  if (prevTail) {
    let bestScore = -Infinity, bestK = 0;
    for (let kk = -tol; kk <= tol; kk += 8) {     // coarse pass (stride 2)
      let dot = 0;
      for (let j = 0; j < Hs; j += 2) dot += input[ip + kk + j] * prevTail[j];
      if (dot > bestScore) { bestScore = dot; bestK = kk; }
    }
    for (let kk = bestK - 7; kk <= bestK + 7; kk++) { // fine pass (every sample)
      let dot = 0;
      for (let j = 0; j < Hs; j++) dot += input[ip + kk + j] * prevTail[j];
      if (dot > bestScore) { bestScore = dot; bestK = kk; }
    }
    k = bestK;
  }
  const p = ip + k;
  for (let j = 0; j < Hs; j++)     out[op + j] += input[p + j] * (j / Hs);
  for (let j = Hs; j < frame; j++) out[op + j] += input[p + j] * ((frame - j) / Hs);
  prevTail = input.subarray(p + Hs, p + frame);  // kept half, reused as next match target
  op += Hs; ip += Ha;
}

Two details that matter:

  • Synthesis is pinned to a fixed Hs grid with a triangular window, so the overlap-add always sums to exactly 1 — no gain wobble. Only the analysis position ip + k moves, within ±256 samples of the ideal.
  • The similarity metric is a dot product between the candidate frame and prevTail (the half-window kept from the last frame). Matching on the actual preserved tail — not a synthetic window — is what kills the buzz.

The trade-off is real: this runs synchronously on the main thread. A three-minute song stretches in well under a second, but a six-minute track visibly stalls the tab for a beat. Fine for a local tool, not for a streaming service.

Part 3 — Encoding MP3 in the browser

The output is 128 kbps mono MP3, encoded with lamejs, a pure-JavaScript MP3 encoder that I vendor locally — the one piece of the stack that isn't hand-rolled. The interesting part is staying responsive: lamejs's encodeBuffer is synchronous, so I feed it in chunks and yield to the event loop every few chunks:

const CHUNK = 1152 * 32;
let sinceYield = 0;
for (let off = 0; off < pcm.length; off += CHUNK) {
  const buf = encoder.encodeBuffer(pcm.subarray(off, off + CHUNK));
  if (buf.length) parts.push(copyOf(buf));
  if (++sinceYield >= 4) { sinceYield = 0; onProgress(off / pcm.length); await sleep(0); }
}

The await sleep(0) (a zero-delay timeout) hands control back to the browser between chunks, so the progress bar animates and the page never hard-freezes, even on long files. (sleep is just new Promise(r => setTimeout(r, ms)).)

Storage: IndexedDB and a tiny LRU

Decoded PCM is large, so each adjusted song is persisted to IndexedDB as Int16Array PCM plus a small metadata record (id, name, detected BPM, target BPM, drum settings, order). A 3-song in-memory LRU (~60 MB) keeps the songs you are actively working on out of a re-decode on every interaction; cache misses fall back to the database.

The honest trade-offs

I would rather list these than have someone find them in the comments:

  • Synchronous stretch. No Web Worker, no AudioWorklet. Files over ~6 minutes cause a brief, visible stall.
  • Extreme ratios sound worse. Going from 52 to 180 BPM is a 3.46× dilation; WSOLA preserves intelligibility but timbre obviously shifts. Modest changes (±15%) are near-transparent.
  • Beat detection is good, not perfect. Steady-tempo pop/EDM: reliable. Free-tempo or atonal material: it guesses. There is a manual nudge for exactly this.
  • MP3 only, 128 kbps mono. Fine for workout audio; not a mastering format.

Try it

If you want to hear the result: 180 Running Music Editor takes a file, detects the tempo, and stretches it to 180 (or any cadence from 50 to 200) in your browser. The DSP above is the whole engine. Happy to paste the unabridged detectBPM and stretchOLA functions if anyone wants to see the full ~100 lines — both had failure modes that took a while to track down.