Capturing system audio in Electron on macOS, Windows and Linux without a virtual driver
If your Electron app needs to hear what the computer is playing (the other side of a Zoom call, a video, a meeting), the usual advice is "install BlackHole / VB-Cable and set up a Multi-Output device". That works on your machine and fails for real users: they won't install a kernel extension, and if they do, their headphones go quiet.
You don't need any of it. Modern Electron (we're on 42) gives you system audio loopback through getDisplayMedia. Here is the setup we run in production in Interview Copilot (a desktop overlay that transcribes the interviewer in real time), plus the failure modes that only showed up with paying users.
1. Main process: answer getDisplayMedia with audio: 'loopback'
const { session, desktopCapturer } = require('electron'); session.defaultSession.setDisplayMediaRequestHandler((request, callback) => { let answered = false; const reply = (arg) => { if (answered) return; // callback may be called only once answered = true; try { callback(arg); } catch (e) { /* request already cancelled */ } }; desktopCapturer.getSources({ types: ['screen'] }) .then((sources) => { if (!sources.length) return reply({}); // video is formally required; we only keep the audio track reply({ video: sources[0], audio: 'loopback' }); }) .catch(() => reply({})); // usually: Screen Recording permission revoked }, { useSystemPicker: false }); Two things that bit us:
-
callbackthrows if the request was already cancelled (window closed, stream aborted). In the naive.then(cb).catch(() => cb({}))version the exception escapes from thecatchhandler and becomes anunhandledRejection. Guard it. - You can't return audio without video.
callback({ audio: 'loopback' })is rejected with "Invalid capture constraints". So ifgetSources()fails, you lose audio too.
What you get per platform:
| Platform | What powers it | Permission |
|---|---|---|
| macOS 14.4+ | ScreenCaptureKit | "Screen & System Audio Recording" (TCC) |
| Windows 10/11 | WASAPI loopback | none |
| Linux (PulseAudio and PipeWire) | Chromium reads the sink directly | none on X11 |
The Linux row surprised us. We expected to need a separate code path; in our tests on Ubuntu 24.04 (X11) loopback produced a "System audio" track even on a machine with zero input devices. Wayland is another story: the screencast portal is required, and when getSources() fails there, audio goes with it (see the "no audio without video" point above).
2. Renderer: try several constraint shapes
Different Chromium/macOS builds reject different constraint combinations with the same "Invalid capture constraints" error. For desktop loopback the browser doesn't apply mic processing anyway, so start with the most permissive request and fall back:
async function getDisplayStream() { const attempts = [ { video: true, audio: true }, { video: true, audio: { echoCancellation: false, noiseSuppression: false, autoGainControl: false } }, { video: { width: 1, height: 1 }, audio: true }, ]; let last; for (const c of attempts) { try { return await navigator.mediaDevices.getDisplayMedia(c); } catch (e) { if (e.name === 'NotAllowedError') throw e; // permission denied: stop trying last = e; } } throw last; } const stream = await getDisplayStream(); stream.getVideoTracks().forEach((t) => t.stop()); // we only need audio if (!stream.getAudioTracks().length) { // macOS: Screen Recording permission missing. Tell the user, don't fail silently. } We had a user stuck on this error because the original code had only two attempts. The third shape fixed it.
3. AudioWorklet: PCM chunks + a cheap VAD
Speech-to-text APIs bill by audio seconds. Most of a call is silence, so gate it before it leaves the machine. An AudioWorkletProcessor runs off the main thread (no glitches when the UI is busy, unlike ScriptProcessorNode):
class PCMProcessor extends AudioWorkletProcessor { constructor() { super(); this.buf = []; this.target = 2048; this.gain = 1; this.vadThresh = 0.005; // RMS on the RAW signal, before gain this.hangoverSec = 1.0; // keep sending after the level drops this.voiced = false; this.hangoverUntil = 0; this.preroll = []; this.prerollMax = 14; // ~600 ms at 48 kHz } process([input]) { const ch = input && input[0]; if (!ch) return true; let peak = 0, sumSq = 0; for (const s of ch) { const a = Math.abs(s); if (a > peak) peak = a; sumSq += s * s; } const rms = Math.sqrt(sumSq / ch.length); if (rms >= this.vadThresh) { this.voiced = true; this.hangoverUntil = currentTime + this.hangoverSec; } else if (this.voiced && currentTime >= this.hangoverUntil) this.voiced = false; // soft normalisation towards peak 0.7, capped at x6 if (peak > 0.001) this.gain += (Math.min(6, Math.max(1, 0.7 / peak)) - this.gain) * 0.05; for (const s of ch) this.buf.push(s * this.gain); while (this.buf.length >= this.target) { const pcm = toInt16(this.buf.splice(0, this.target)); if (this.voiced) { while (this.preroll.length) this.port.postMessage({ pcm: this.preroll.shift() }); this.port.postMessage({ pcm: pcm.buffer, peak }, [pcm.buffer]); } else { this.preroll.push(pcm.buffer); if (this.preroll.length > this.prerollMax) this.preroll.shift(); this.port.postMessage({ peak }); // level only, for the UI and the watchdog } } return true; } } function toInt16(f) { const out = new Int16Array(f.length); for (let i = 0; i < f.length; i++) { const s = Math.max(-1, Math.min(1, f[i])); out[i] = s < 0 ? s * 0x8000 : s * 0x7fff; } return out; } registerProcessor('pcm-processor', PCMProcessor); Why each knob exists:
- Pre-roll (~600 ms): the first syllable is usually below the threshold. Without it, "So, tell me about…" arrives as "…tell me about".
- Hangover (1 s): short pauses inside a sentence don't cut the stream, and the STT's own end-of-utterance detector gets the trailing silence it needs to commit a segment.
- Detect on the raw signal, normalise after: otherwise the gain stage amplifies room noise above your threshold.
- Post a message even in silence: you will need it for the watchdog below.
Connect the worklet through a muted gain node so it keeps running without playing audio back:
const ctx = new AudioContext(); await ctx.audioWorklet.addModule('pcm-worklet.js'); const node = new AudioWorkletNode(ctx, 'pcm-processor', { channelCount: 1 }); ctx.createMediaStreamSource(stream).connect(node); const mute = ctx.createGain(); mute.gain.value = 0; node.connect(mute).connect(ctx.destination); 4. The stream dies silently. Four ways.
This is the part no tutorial mentions. Status says "Listening", nothing is being heard, and the user finds out 30 minutes into a call. Each of these happened to a real user:
- The track ends. Windows switched the output device (headphones plugged in, driver update), or the user stopped sharing in the call app. Listen for
endedon the audio track andinactiveon the stream, then restart after ~400 ms (the event fires before the OS hands over the new device). Don't react tomute: that's just a pause in the call. - The
AudioContextgets suspended. Windows does this on screen lock, power-source change, device switch. The track is alive, so (1) never fires; the worklet just stops producing frames. Listen tostatechange, callresume(), and do a full restart if that fails. - Everything looks alive, but no frames arrive. Driver hands out empty buffers. No event tells you. The only way is to measure: record the time of the last worklet message and restart if it's older than ~25 s. (We tried shorter; an interviewer reading your CV in silence for 15 s triggered pointless restarts.)
- Two restarts race each other. (1), (2) and (3) are independent triggers, and a device switch often fires several of them at once.
start()has threeawaits before it setsrunning = true, so the guard is open for hundreds of milliseconds and a second start overwrites the first stream. The orphan keeps sending PCM forever: duplicated transcripts, double STT bill. Fix: astartingflag released infinally, plus a generation counter so astop()that lands mid-start invalidates the in-flight start:
let running = false, starting = false, gen = 0; async function start() { if (running || starting) return; starting = true; const myGen = ++gen; try { /* getDisplayStream, AudioContext, addModule, listeners, watchdog… */ if (myGen !== gen) { stop(); return false; } // stopped while we were awaiting running = true; return true; } finally { starting = false; // in finally: a failed start must not block every future start } } function stop() { running = false; starting = false; gen++; /* clear watchdog, disconnect nodes, ctx.close(), stop tracks */ } 5. macOS permissions after an update
On macOS the loopback depends on the Screen Recording permission, and TCC matches it to your code signature. While our builds were unsigned, the cdhash changed every release, so macOS stopped recognising the app after each update even though the checkbox was still ticked. We worked around it with tccutil reset ScreenCapture <bundle-id> on version change (no sudo needed for your own bundle id).
After we started signing and notarising, the signature became stable, the permission survives updates on its own, and that reset turned into the bug: it removed a perfectly valid permission. If you ship unsigned builds, reset; once you sign, reset exactly once on the unsigned→signed transition and never again.
Two more macOS details:
-
systemPreferences.getMediaAccessStatus('screen')tells you the real state, so you can show a "check audio" screen before the call instead of a support ticket after it. - macOS applies a newly granted Screen Recording permission only to a new process. Offer a "Restart app" button (
app.relaunch(); app.quit();), otherwise users tick the box and nothing changes.
Summary
-
setDisplayMediaRequestHandler+audio: 'loopback'gives you system audio on macOS 14.4+, Windows and Linux/X11 without virtual drivers. - Ask with several constraint shapes; video is mandatory, so drop the track afterwards.
- Gate silence in an AudioWorklet with pre-roll and hangover; it cuts your STT bill and improves segmentation.
- Assume the stream will die: watch
ended/inactive,statechange, and frame arrival times, and makestart()race-safe.
Drafted with an AI assistant from our production code and incident notes.