soundcard developer on retainer: all_microphones() default include_loopback=False omits loopback capture devices — get_microphone('Stereo Mix') raises RuntimeError; fallback to physical desk microphone records room noise instead of system audio; 100% of podcast QA recordings unusable for 3 weeks — include_loopback=True fix — 3 weeks — soundcard developer on monthly retainer

soundcard 0.4.2 • Python 3.9; mics = soundcard.all_microphones(); loopback = soundcard.get_microphone('Stereo Mix'); except RuntimeError: loopback = soundcard.default_microphone() • Southfield Soundcard Ltd. (podcast QA monitoring platform; 500 recordings/month; system designed to capture broadcast audio output via loopback device and analyze for audio defects — clipping, compression artifacts, background bleed; soundcard.all_microphones() default include_loopback=False filters loopback capture devices from returned list on Windows 10 WASAPI; soundcard.get_microphone('Stereo Mix') raises RuntimeError: “Stereo Mix” not found in list of microphones; except block falls back to soundcard.default_microphone() (physical USB desk microphone); 100% of QA recordings capture open-plan office room noise instead of broadcast audio; QA team reports 0 usable recordings for 3 weeks; fix: soundcard.all_microphones(include_loopback=True); select loopback device via m.isloopback property; recordings capture system audio; 1.5h retainer engagement

Southfield Soundcard Ltd. built a quality assurance monitoring platform for a podcast production company. The platform ran on the same Windows workstation used for broadcast, and its purpose was to record the final audio output stream as it went out to the audience — capturing any clipping, sudden silence, compression artifacts, or background music bleed that the live operator might miss. The developer chose soundcard for the loopback capture because it requires no C extension or PortAudio installation, running entirely through Python’s cffi bindings to the Windows WASAPI API. The recording loop was designed to call soundcard.get_microphone('Stereo Mix') to obtain a handle to the loopback capture device (a Windows audio feature that exposes a virtual microphone representing whatever the system is currently playing), then record 60 seconds of audio per episode segment. During development on the developer’s personal workstation, ‘Stereo Mix’ appeared in the device list and the system worked correctly. After deployment to the production workstation — a different machine with a different audio driver — get_microphone('Stereo Mix') raised RuntimeError: “Stereo Mix” not found in list of microphones. A defensive except RuntimeError block fell back to soundcard.default_microphone(), which resolved to the USB desk microphone sitting on the producer’s desk. No error was logged at the QA review tier. For the next three weeks, 500 recordings per month captured open-plan office room noise — keyboard clicks, ambient conversation, the HVAC system — with no trace of the actual broadcast audio. The QA team reviewed the recordings, found nothing useful in them, and assumed the platform was still being configured. A soundcard retainer developer was engaged when a producer finally pulled a recording and listened to it.

The root cause was identified in 15 minutes. soundcard.all_microphones() accepts an include_loopback parameter (default False) that controls whether WASAPI loopback capture devices are included in the returned list. On Windows, loopback capture devices are a separate category of audio endpoint from physical microphones: they appear as virtual microphone devices that capture whatever the system’s output endpoint is playing, and they carry the isloopback=True property in soundcard. With the default include_loopback=False, all_microphones() returns only physical input devices (the USB desk microphone, any built-in microphone). The loopback device — named ‘Stereo Mix’ on some audio drivers and ‘CABLE Output’ or other names on others — is excluded entirely. soundcard.get_microphone('Stereo Mix') calls all_microphones(include_loopback=False) internally and searches for a device whose name contains the given string; since loopback devices are excluded, no match is found and a RuntimeError is raised. The developer had not tested what happened when the except RuntimeError block executed, and the fallback to default_microphone() silently replaced the intended loopback device with a physical microphone. The fix had two parts: (1) change the device enumeration call to soundcard.all_microphones(include_loopback=True); (2) replace the name-based device selection with an isloopback property filter, which is robust across different audio drivers and device names. After the fix, every recording session correctly captured the broadcast audio stream. A 1000 Hz test tone played through the system was confirmed at the correct frequency via FFT on the first recording, and room noise was absent from all subsequent QA recordings.

The annotated buggy and fixed loopback capture code, with a device enumeration diagnostic helper:

# Southfield Soundcard Ltd. — soundcard 0.4.2 include_loopback=False default
# soundcard 0.4.2; Python 3.9; Windows 10 WASAPI
# Pipeline: system audio output → loopback capture → QA defect detection
# Problem: all_microphones(include_loopback=False) omits loopback devices
#          get_microphone('Stereo Mix') raises RuntimeError (not in list)
#          except block falls back to default_microphone() (physical desk mic)
#          500 QA recordings/month contain room noise, not broadcast audio
# Fix: all_microphones(include_loopback=True); select via isloopback property

import numpy as np
import soundcard


SAMPLE_RATE = 44100  # Hz
RECORD_DURATION_S = 60


# ── Device diagnostic ────────────────────────────────────────────────────────

def list_all_devices() -> None:
    """
    Log all microphone devices with and without include_loopback.
    Shows exactly which devices are hidden by the default include_loopback=False.
    Run this first on any new deployment machine to verify loopback availability.
    """
    mics_no_loopback = soundcard.all_microphones(include_loopback=False)
    mics_with_loopback = soundcard.all_microphones(include_loopback=True)

    print("Microphones (include_loopback=False):")
    for m in mics_no_loopback:
        print(f"  id={m.id!r:40s}  name={m.name!r}  loopback={m.isloopback}")

    print()
    print("Microphones (include_loopback=True):")
    for m in mics_with_loopback:
        marker = " ← LOOPBACK DEVICE" if m.isloopback else ""
        print(f"  id={m.id!r:40s}  name={m.name!r}  loopback={m.isloopback}{marker}")

    loopback_devices = [m for m in mics_with_loopback if m.isloopback]
    if not loopback_devices:
        print()
        print("WARNING: No loopback devices found with include_loopback=True.")
        print("On Windows: enable 'Stereo Mix' in Sound > Recording > Show Disabled Devices")
        print("Or install a virtual audio cable (VB-CABLE, BlackHole on macOS).")


# ── BUGGY recorder ───────────────────────────────────────────────────────────

def record_qa_buggy(duration_s: float = RECORD_DURATION_S) -> np.ndarray:
    """
    BUG: all_microphones() default include_loopback=False hides loopback devices.
    get_microphone('Stereo Mix') raises RuntimeError on machines where the
    loopback device name differs ('CABLE Output', 'Realtek Stereo Mix', etc.).
    except block silently falls back to default_microphone() (physical desk mic).
    Records room noise instead of system audio. No error logged.
    """
    try:
        # BUG: all_microphones(include_loopback=False) is the default
        # 'Stereo Mix' not in list → RuntimeError
        loopback = soundcard.get_microphone('Stereo Mix')
    except RuntimeError:
        # BUG: silent fallback to physical microphone
        loopback = soundcard.default_microphone()

    with loopback.recorder(samplerate=SAMPLE_RATE) as rec:
        data = rec.record(numframes=int(SAMPLE_RATE * duration_s))
    return data  # shape: (numframes, num_channels), dtype: float32


# ── FIXED recorder ────────────────────────────────────────────────────────────

def get_loopback_device():
    """
    FIX: use include_loopback=True and select by isloopback property.
    Robust across device name variations: 'Stereo Mix', 'CABLE Output',
    'Realtek Stereo Mix', 'VB-Audio Virtual Cable' — all have isloopback=True.
    Raises RuntimeError with a helpful message if no loopback device is available.
    """
    all_mics = soundcard.all_microphones(include_loopback=True)  # FIX
    loopback_devices = [m for m in all_mics if m.isloopback]  # FIX: use property

    if not loopback_devices:
        raise RuntimeError(
            "No loopback capture device found. "
            "On Windows: enable 'Stereo Mix' in Sound Settings > Recording > "
            "Show Disabled Devices, or install VB-CABLE."
        )

    # Use the first loopback device; log its name for debugging
    device = loopback_devices[0]
    print(f"Using loopback device: {device.name!r} (id={device.id!r})")
    return device


def record_qa_fixed(duration_s: float = RECORD_DURATION_S) -> np.ndarray:
    """
    FIX: select loopback device by isloopback property.
    Records system audio output, not room noise.
    Raises RuntimeError with a helpful message if no loopback is available
    (instead of silently recording the desk mic).
    """
    loopback = get_loopback_device()
    with loopback.recorder(samplerate=SAMPLE_RATE) as rec:
        data = rec.record(numframes=int(SAMPLE_RATE * duration_s))
    return data  # shape: (numframes, num_channels), dtype: float32


# ── Loopback verification ─────────────────────────────────────────────────────

def verify_loopback_capture(test_tone_hz: float = 1000.0) -> None:
    """
    Verify loopback device captures system audio (not room noise).
    Requires a test tone to be playing through the system's default speaker.
    Checks that the dominant FFT frequency component matches the test tone.
    """
    import soundcard as sc
    import numpy as np

    # Play test tone through default speaker (requires concurrent thread in production)
    print(f"Verifying loopback: expecting {test_tone_hz} Hz test tone in system audio")

    loopback = get_loopback_device()
    with loopback.recorder(samplerate=SAMPLE_RATE) as rec:
        data = rec.record(numframes=SAMPLE_RATE)  # 1 second

    # Average channels to mono
    mono = data.mean(axis=1) if data.ndim == 2 else data

    # Compute FFT dominant frequency
    fft_magnitude = np.abs(np.fft.rfft(mono))
    freqs = np.fft.rfftfreq(len(mono), d=1.0 / SAMPLE_RATE)
    dominant_freq = float(freqs[np.argmax(fft_magnitude)])

    rms = float(np.sqrt(np.mean(mono ** 2)))
    rms_db = 20 * np.log10(rms) if rms > 0 else -120.0

    print(f"  Dominant frequency: {dominant_freq:.1f} Hz "
          f"(expect: {test_tone_hz:.1f} Hz, tolerance: ±5 Hz)")
    print(f"  RMS level: {rms_db:.1f} dBFS  (expect > -18 dBFS for audible signal)")

    if abs(dominant_freq - test_tone_hz) <= 5.0 and rms_db > -18.0:
        print("  PASS: loopback device capturing system audio correctly")
    else:
        print("  FAIL: loopback may be recording room noise — check device selection")
    print()
    print("Root cause: soundcard.all_microphones(include_loopback=False) default")
    print("  Loopback devices not in list; get_microphone() raises RuntimeError")
    print("  except block silently falls back to default physical microphone")
    print("  500 QA recordings/month contain room noise for 3 weeks")
    print()
    print("Fix: all_microphones(include_loopback=True)")
    print("  Select loopback by m.isloopback property (not by device name)")
    print("  Room noise: 100% of recordings → 0%; broadcast audio confirmed; 1.5h")


if __name__ == '__main__':
    list_all_devices()

How soundcard’s include_loopback parameter, the isloopback property, and Windows WASAPI loopback capture interact — and the correct pattern for system audio recording across platforms

soundcard wraps the native audio API on each platform via cffi: WASAPI on Windows, CoreAudio on macOS, PulseAudio (or ALSA) on Linux. Each platform has a different model for loopback capture. On Windows WASAPI, loopback capture devices are virtual input endpoints that mirror an output endpoint’s audio stream. They appear in the Windows Sound control panel under the Recording tab when “Show Disabled Devices” is enabled. Common names include ‘Stereo Mix’ (Realtek drivers), ‘What U Hear’ (Creative drivers), and ‘CABLE Output’ (VB-Audio Virtual Cable). These names are not guaranteed to be consistent across Windows versions, driver updates, or hardware configurations. Using device names for loopback selection is fragile; using the isloopback property is robust. The include_loopback parameter of soundcard.all_microphones() and soundcard.all_speakers() is the only way to include loopback endpoints in the returned list; there is no separate function for loopback-only enumeration. On macOS, native CoreAudio does not expose loopback capture as a standard device; capturing system audio on macOS requires installing a third-party virtual audio driver such as BlackHole (open source) or Soundflower (deprecated). The virtual driver appears as a standard audio output device; routing audio through it and recording via soundcard requires explicit configuration of macOS audio routing that is outside soundcard’s scope. On Linux, PulseAudio provides monitor sources (named with a .monitor suffix) that capture the output of a sink; these appear in soundcard’s device list when include_loopback=True and have isloopback=True. The practical guidance for cross-platform loopback recording: use soundcard.all_microphones(include_loopback=True) and filter by m.isloopback; test on the actual deployment machine before go-live; on macOS, document that a virtual audio driver must be installed separately; never use a bare except RuntimeError that silently falls back to a physical microphone, as this hides the absence of a loopback device entirely. The retainer engagement was 1.5h: 0.5h triage (QA recordings contain room noise; soundcard.all_microphones() output logged on production machine; loopback device absent from list; include_loopback=False default confirmed in soundcard 0.4.2 source); 0.5h root cause (WASAPI loopback endpoint behavior confirmed on Windows 10; get_microphone() RuntimeError path confirmed; default_microphone() fallback in except block identified; device list comparison with and without include_loopback=True confirms loopback device present but hidden); 0.25h fix (include_loopback=True; isloopback property filter; bare except block replaced with explicit RuntimeError with helpful message); 0.25h validation (1000 Hz test tone FFT confirms correct loopback capture; room noise absent; 10 test recordings all pass; 1.5h total). Hours logged to HourTab with per-session breakdown.

Related retainer posts


Track retainer hours without a client portal

HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.

See pricing →