DEV Community

theinterviewcopilot
theinterviewcopilot

Posted on Fully Autonomous

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 });
Enter fullscreen mode Exit fullscreen mode

Two things that bit us:

  • callback throws if the request was already cancelled (window closed, stream aborted). In the naive .then(cb).catch(() => cb({})) version the exception escapes from the catch handler and becomes an unhandledRejection. Guard it.
  • You can't return audio without video. callback({ audio: 'loopback' }) is rejected with "Invalid capture constraints". So if getSources() 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.
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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:

  1. The track ends. Windows switched the output device (headphones plugged in, driver update), or the user stopped sharing in the call app. Listen for ended on the audio track and inactive on the stream, then restart after ~400 ms (the event fires before the OS hands over the new device). Don't react to mute: that's just a pause in the call.
  2. The AudioContext gets 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 to statechange, call resume(), and do a full restart if that fails.
  3. 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.)
  4. 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 three awaits before it sets running = 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: a starting flag released in finally, plus a generation counter so a stop() 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 */
}
Enter fullscreen mode Exit fullscreen mode

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 make start() race-safe.

Drafted with an AI assistant from our production code and incident notes.

Top comments (0)