I wanted a "stereo width" control for an audio tool that runs entirely in the browser. The classic way to build one is mid/side processing: convert left/right into two new signals, scale one of them, convert back. It is a few lines of arithmetic, and the browser already gives you everything else: decodeAudioData to read a file, OfflineAudioContext to render, and a small WAV writer to hand the result back as a download. This post walks through the whole pipeline and runs the maths under plain node so you can check it.
Mid and side in one paragraph
Take a stereo pair. The mid signal is what both channels have in common: (L + R) / 2. The side signal is what differs: (L - R) / 2. A sound panned dead centre, typically a lead vocal or a kick drum, is identical in both channels, so it lives entirely in mid and contributes nothing to side. A sound panned hard left appears only in L, so it splits evenly between mid and side.
Going back is just as simple: L = mid + side and R = mid - side. If you multiply side by a gain before decoding, you get a width control. A gain of 0 collapses the mix to mono, 1 leaves it unchanged, and values above 1 push the stereo image wider. Subtracting instead of keeping the side signal is the same arithmetic that powers the old "karaoke" trick, just used for a different goal.
The code
Everything below operates on Float32Arrays, which is exactly what AudioBuffer.getChannelData() returns. That means the core can be tested in node with synthesised tones, no audio hardware needed.
// Mid/side processing + 16-bit WAV export on plain Float32Arrays.
// In the browser the arrays come from AudioBuffer.getChannelData();
// here we synthesise them so the whole thing runs under node.
function encode(left, right) { // L/R -> mid/side
const n = Math.min(left.length, right.length);
const mid = new Float32Array(n), side = new Float32Array(n);
for (let i = 0; i < n; i++) {
mid[i] = (left[i] + right[i]) / 2;
side[i] = (left[i] - right[i]) / 2;
}
return { mid, side };
}
function decode(mid, side, sideGain = 1) { // mid/side -> L/R, with a width knob
const n = mid.length;
const left = new Float32Array(n), right = new Float32Array(n);
for (let i = 0; i < n; i++) {
left[i] = mid[i] + side[i] * sideGain;
right[i] = mid[i] - side[i] * sideGain;
}
return [left, right];
}
function rms(a) {
let s = 0;
for (let i = 0; i < a.length; i++) s += a[i] * a[i];
return Math.sqrt(s / a.length);
}
// Interleaved 16-bit PCM WAV, little-endian, 44-byte header.
function toWav(channels, sampleRate) {
const nCh = channels.length, n = channels[0].length;
const dataBytes = n * nCh * 2;
const buf = new ArrayBuffer(44 + dataBytes);
const v = new DataView(buf);
const str = (o, s) => { for (let i = 0; i < s.length; i++) v.setUint8(o + i, s.charCodeAt(i)); };
str(0, 'RIFF'); v.setUint32(4, 36 + dataBytes, true); str(8, 'WAVE');
str(12, 'fmt '); v.setUint32(16, 16, true); v.setUint16(20, 1, true);
v.setUint16(22, nCh, true); v.setUint32(24, sampleRate, true);
v.setUint32(28, sampleRate * nCh * 2, true); v.setUint16(32, nCh * 2, true);
v.setUint16(34, 16, true); str(36, 'data'); v.setUint32(40, dataBytes, true);
let o = 44;
for (let i = 0; i < n; i++) {
for (let c = 0; c < nCh; c++) {
const x = Math.max(-1, Math.min(1, channels[c][i]));
v.setInt16(o, x < 0 ? x * 0x8000 : x * 0x7fff, true);
o += 2;
}
}
return Buffer.from(buf);
}
A few notes on the details:
-
The 1/2 factor. Using
(L + R) / 2instead ofL + Rkeeps mid inside the same range as the inputs, so a full-scale mono signal does not clip. The decode step then needs no extra scaling, which keeps the round trip exact. -
Clamping in
toWav. After a width boost the samples can exceed 1.0. Float audio tolerates that, but 16-bit integers do not, so the encoder clamps. If you boost a lot, normalise first. -
Asymmetric scaling. 16-bit PCM spans -32768 to 32767, which is why negative samples multiply by
0x8000and positive ones by0x7fff. - Interleaving. WAV stores samples frame by frame: L0 R0 L1 R1 and so on. The inner loop over channels does exactly that.
Running it
The test at the bottom builds a 440 Hz "vocal" panned centre and a 330 Hz "guitar" panned hard left, then checks the maths. Output from node v26:
mid RMS : 0.3808
side RMS: 0.1414 (guitar/2 = 0.1414)
round-trip max error: 5.96e-8
width 0 -> L==R ? true
WAV bytes: 64044 expected: 64044
header: RIFF WAVE rate 8000
The side RMS matches the prediction: a 0.4-amplitude sine has an RMS of 0.4 / sqrt(2), and mid/side halves the left-only component, giving 0.1414. The round trip is exact to float precision, and a width of 0 produces identical channels.
Wiring it to the Web Audio API
In the browser, replace the synthesised tones with a decoded file. OfflineAudioContext is only needed here to decode at a known sample rate and, if you want, to run built-in nodes (an EQ, say) before your own processing.
async function widen(file, sideGain) {
const bytes = await file.arrayBuffer();
const ctx = new OfflineAudioContext(2, 1, 44100); // length is irrelevant for decoding
const audio = await ctx.decodeAudioData(bytes);
const [l, r] = [audio.getChannelData(0), audio.getChannelData(audio.numberOfChannels > 1 ? 1 : 0)];
const { mid, side } = encode(l, r);
const out = decode(mid, side, sideGain);
const wav = toWav(out, audio.sampleRate); // in the browser, build a Blob from the ArrayBuffer
return new Blob([wav], { type: 'audio/wav' });
}
Two browser-specific points. First, Buffer does not exist there, so return the ArrayBuffer from toWav directly and wrap it in a Blob; the node version wraps it only so fs.writeFileSync accepts it. Second, a mono file only has one channel, which is why the snippet falls back to channel 0 for the right side. Mid/side on a mono file is pointless, since side is zero, so you may want to detect that and skip the control.
Limits worth knowing
Mid/side is not a magic separator. Anything that sits in the centre but should be treated differently, for example vocal and bass both centred, will move together. Reverb tails are usually decorrelated between channels, so they land in side and get amplified when you widen. And heavy widening can make a mix collapse badly when summed to mono, because the side energy cancels. Always listen in mono after pushing the width past 1.2 or so.
Where I used it
This is the same channel arithmetic behind the in-browser tools I work on. If you want to hear what removing the centre does to a real song, without writing any code, the free in-browser tool at ultimatevocalremovertool.com is the practical version of the idea. For your own projects, the snippet above is enough to build a width slider, a mono-compatibility check, or a bass-to-centre filter in an afternoon.
Top comments (0)