Dev.to WebDev ๐Ÿ›  Dev ๐Ÿ‘ 0 ๐Ÿ“– 7 min read

What I learned building real-time 8D audio in the browser with the Web Audio API

"8D audio" is the effect where a song seems to circle around your head when you wear headphones. Most of the 8D tracks on YouTube are pre-rendered: someone ran the song through a DAW and uploaded the result. I wanted it

"8D audio" is the effect where a song seems to circle around your head when you wear headphones. Most of the 8D tracks on YouTube are pre-rendered: someone ran the song through a DAW and uploaded the result.

I wanted it live, on any song you're already playing, with nothing uploaded anywhere. That became 8Dfy, a browser extension for YouTube, YouTube Music, Apple Music and Spotify Web. Everything runs in the Web Audio API, inside the tab.

The basic version takes about 20 lines. Making it sound good took months, and nearly every improvement started as a bug I didn't understand. These are the ones worth writing down.

1. Getting at the page's audio

The entry point is createMediaElementSource:

const ctx = new AudioContext();
const source = ctx.createMediaElementSource(videoElement);
source.connect(ctx.destination); // nothing is audible until you do this

Two things surprised me:

  • It's a one-way door. Once a media element is connected, its sound only comes out through your graph. If your graph breaks, the video goes silent, so I added a watchdog that checks the processed signal is still alive.
  • One source per element, ever. Calling it a second time on the same <video> throws InvalidStateError. YouTube reuses its video element across navigations, so the source must be created once and kept.

2. The classic 8D: a panner and a slow oscillator

The core effect is a StereoPannerNode whose pan swings between -1 and 1 every few seconds:

const panner = ctx.createStereoPanner();
const lfo = ctx.createOscillator();   // the "low-frequency oscillator"
lfo.frequency.value = 0.15;           // one full swing about every 7 s
const depth = ctx.createGain();
depth.gain.value = 1;                 // pan range: -1 .. 1

lfo.connect(depth).connect(panner.pan);
lfo.start();

The bug: my first version moved pan from requestAnimationFrame. It worked until you switched tabs. Browsers pause rAF in background tabs, so the music froze wherever it happened to be, often stuck in one ear.

The fix: never animate audio from the main thread. An OscillatorNode connected to an AudioParam runs on the audio thread, keeps going in background tabs, and doesn't stutter when the page is busy. Every moving part of 8Dfy now works this way, including the 3D positions below.

3. Real 3D with HRTF, and the stereo trap

Panning only moves sound left and right. For sound that seems to come from in front of you, behind you or above you, the browser has a built-in HRTF engine (head-related transfer function):

const panner = new PannerNode(ctx, {
  panningModel: 'HRTF',
  rolloffFactor: 0,          // don't let distance turn the volume down
  positionX: 0, positionY: 0, positionZ: -1,
});

positionX/Y/Z are AudioParams too, so oscillators can drive them. An orbit is just x = sin(t) and z = -cos(t), which is two oscillators 90ยฐ apart. I build each path as a PeriodicWave, so the shape (orbit, figure-8, drift) is a few harmonic coefficients.

The bug: I put a source hard right and still heard it hard left. A PannerNode defaults to channelCountMode: 'clamped-max', which lets a stereo input through largely untouched, so the song's own stereo image beat the 3D position. Downmixing to mono fixed the direction but cost 6 dB and made out-of-phase content sound hollow.

The fix: split the channels and give each one its own panner, with channelCount: 1 and channelCountMode: 'explicit'. The two sources follow the same path a few degrees apart. The song keeps its width, and the position really controls the direction.

There was one more surprise. Below about 150 Hz your head casts no acoustic shadow, so both panners output nearly the same bass, and their sum is up to +6 dB. Bass-heavy tracks distorted in 3D mode only, so the 3D path now has its own low-frequency compensation.

4. "Surround": splitting the song into bands

Surround mode splits the music into three bands. The lows stay centred, the mids orbit, and the highs follow at half depth.

The bug: I made the split with single lowpass and highpass biquads, and the result had a ~19 dB hole at each crossover point (250 Hz and 2 kHz). At the cutoff frequency the two filters are out of phase, so they cancel.

The fix: use a Linkwitz-Riley crossover, which is two Butterworth biquads in series. Its bands add back up flat. One detail to know: for lowpass and highpass, the Web Audio Q is in dB, so Butterworth is -3.01, not 0.707:

const BUTTERWORTH_Q_DB = 20 * Math.log10(Math.SQRT1_2); // โ‰ˆ -3.01

function lr4(ctx, type, freq) {
  const a = new BiquadFilterNode(ctx, { type, frequency: freq, Q: BUTTERWORTH_Q_DB });
  const b = new BiquadFilterNode(ctx, { type, frequency: freq, Q: BUTTERWORTH_Q_DB });
  a.connect(b);
  return { input: a, output: b };
}

The bands now sum within 0.2 dB. I also removed a 7 ms "width" delay on the highs that combed against the mids, putting a 7 dB dip right through the vocal presence range.

5. Slowed + Reverb

"Slowed + reverb" is mostly two things.

Slowed is a tape-style speed change: lower speed, lower pitch.

video.preservesPitch = false;
video.playbackRate = 0.85;

The bug: I left preservesPitch off when the user went back to normal speed. Then YouTube's own 1.5x menu turned every video into chipmunks for anyone with the extension. Now pitch only follows speed while the extension is the one changing it.

Reverb is a ConvolverNode, and you need an impulse response for it. I generate one in code instead of shipping audio files. My first attempt was white noise with a fade, and it sounded like a metallic spray. A convincing hall needs:

  • a handful of sparse early reflections, alternating between the ears;
  • a diffuse tail that decays exponentially (exp(-6.91ยทt / RT60));
  • a lowpass that sweeps from 12 kHz down to 2 kHz across the tail, because real rooms absorb high frequencies first.

6. A 300% volume booster that doesn't crackle

Turning gain up past 1.0 is easy. Doing it without distortion is the hard part. My chain ends like this:

  1. A DynamicsCompressorNode set as a safety limiter (threshold -1 dB, ratio 20, 1 ms attack). It's set so normal music never reaches it, which avoids audible pumping.
  2. A soft clipper: a WaveShaperNode that leaves the signal unchanged below 0.85, then curves smoothly toward a 0.87 ceiling. A 1 ms attack lets the leading edge of a drum hit through, and the soft clipper catches it.

The bug: the soft clipper uses oversample: '4x' to avoid aliasing, but I measured peaks of 0.92 on impulses and 1.01 on gated transients against that 0.87 ceiling. The filter that brings the 4x signal back down rings, so the oversampled stage overshoots its own curve. Smooth test signals like pink noise never revealed it, but real music went over the ceiling on 12.6% of frames in 3D mode.

The fix: add a second WaveShaperNode with oversample: 'none' that hard-clips at 0.87. Without oversampling there's no resampling, so nothing rings. It only ever touches the rare overshoot sample, so it's inaudible.

The lesson: test against real music, not just test signals.

7. Beat detection without the main thread

The Beat Sync and Auto DJ features need to know where the kicks are.

The bug: I polled an AnalyserNode every 80 ms. An analyser only holds its last fftSize samples (about 21 ms), so each poll saw about a quarter of the audio and missed most kicks. Its byte output also clips at -30 dB, so a loud bassline looked identical to a kick.

The fix: a tiny AudioWorkletProcessor that sees every sample. It computes the RMS of a low-passed mono signal and posts it about every 10.7 ms, stamped with the audio clock instead of Date.now():

class BeatTap extends AudioWorkletProcessor {
  process([input]) {
    const ch = input[0];
    if (ch) for (let i = 0; i < ch.length; i++) this.sum += ch[i] * ch[i], this.n++;
    if (++this.blocks >= 4) {
      this.port.postMessage({ t: currentTime, rms: Math.sqrt(this.sum / (this.n || 1)) });
      this.blocks = this.sum = this.n = 0;
    }
    return true;
  }
}

On the main thread, a sample counts as a kick if it is:

  • above -40 dBFS,
  • 38% louder than the running average of the last second,
  • at least 260 ms after the previous kick.

For tempo, I take the median gap between kicks, fold it into 70โ€“160 BPM, then average the gaps that agree with it. The median alone read 120 BPM as 125, because the timing lands on a grid of fixed report intervals.

8. Spotify Web

Spotify's web player can't be processed from inside the page the way YouTube's can. Instead, the extension captures the tab's audio:

  1. The user clicks the toolbar icon. This is the user action Chrome requires before tab capture.
  2. The background service worker calls chrome.tabCapture.getMediaStreamId({ targetTabId }).
  3. Service workers can't run an AudioContext, so an offscreen document opens the stream with getUserMedia({ audio: { mandatory: { chromeMediaSource: 'tab', chromeMediaSourceId } } }), runs the same effect chain and plays the result.

It works well, but speed-based effects like Slowed aren't possible this way. You can't change the playback speed of a live audio stream.

What I'd tell myself at the start

  • Drive everything from the audio thread. Use oscillators on AudioParams and AudioWorklets, never rAF or setInterval.
  • Measure, don't guess. Most of my "it sounds off" problems turned out to be specific numbers: a 19 dB notch, a 6 dB bass sum, a 0.92 overshoot.
  • Test with real music. Pink noise passed every check that a real song failed.
  • Read the spec defaults. channelCountMode, Q in dB and preservesPitch were each behind one of these bugs.

If you want to hear the result, 8Dfy is free on the Chrome Web Store, and there's a free 8D converter on the site for audio files you already have. Put on headphones first. I'm happy to go deeper on any of these in the comments.

๐Ÿ“ฐ Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes โ€” full credit and traffic to the original publisher.