DEV Community

Darkø Tasevski
Darkø Tasevski

Posted on Originally published at darkotasevski.dev

Capturing macOS system audio with a Core Audio process tap

This one is about recording system audio on macOS, which I needed for a meeting-notes app I'm building for myself, and which has two traps in it that I couldn't find written down together anywhere. The first is a Core Audio process tap that looks completely dead, with every call returning noErr and an IOProc that never fires, even when permissions are fine. The second is what happens when you work around that with ScreenCaptureKit, which is that macOS decides you're sharing your screen and mutes every banner from every app for as long as you record.

The tap that "silently fails"

Process taps arrived in macOS 14.2, and the setup goes like this: we describe what to tap with a CATapDescription, create the tap, then create a private aggregate device that has the tap in its tap list, and read the audio through an IOProc on that aggregate. My first version looked roughly like this:

let tapDesc = CATapDescription(stereoMixdownOfProcesses: [])
AudioHardwareCreateProcessTap(tapDesc, &tapID)

let aggregate: [String: Any] = [
    kAudioAggregateDeviceNameKey: "Tap",
    kAudioAggregateDeviceUIDKey: UUID().uuidString,
    kAudioAggregateDeviceIsPrivateKey: true,
    kAudioAggregateDeviceTapListKey: [[kAudioSubTapUIDKey: tapDesc.uuid.uuidString]],
    kAudioAggregateDeviceTapAutoStartKey: true,
]
AudioHardwareCreateAggregateDevice(aggregate as CFDictionary, &aggregateID)
AudioDeviceCreateIOProcIDWithBlock(&ioProcID, aggregateID, nil) { ... }
AudioDeviceStart(aggregateID, ioProcID)
Enter fullscreen mode Exit fullscreen mode

Every one of those calls returned 0, kAudioDevicePropertyDeviceIsRunning read 0 afterwards, the block was never called, and the WAV file came out as a 44-byte header with nothing behind it. Since nothing returned an error I blamed TCC, spent a good while on permission experiments that changed nothing, and ended up moving the capture to ScreenCaptureKit (more on that below).

When I came back to it months later, two settings in that first version stood out:

  • kAudioAggregateDeviceTapAutoStartKey: true keeps the aggregate idle until a process the tap includes writes audio. On a silent Mac nothing writes, so the device never starts, and you get exactly the "running 0, no callbacks" picture that looks like a permission block.
  • CATapDescription(stereoMixdownOfProcesses: []) is a tap of zero processes, since that initializer takes the processes to include. Together with auto-start that means nothing can ever start the device, silent Mac or not. What we want instead is a global tap that leaves out our own process.

To check the first one, we can write a small probe inside the (sandboxed) app that uses a global tap excluding the app itself, runs the IOProc for 12 seconds and logs only counts and levels. These are the three runs I got:

Auto-start What was playing Result
on a video in the browser running 1, 1088 callbacks, peaks around -1 to -3 dBFS
on nothing running 0, 0 callbacks
off nothing running 1, 1074 callbacks, all -180 dBFS (digital silence)

The second row is the original symptom, reproduced while tccd logged the access as allowed, so auto-start alone is enough to produce it. coreaudiod even says what it's doing, it logs register_autostart_context when the device waits, and Starting tap after waiting for writers once something plays, if you think to look there. The third row is what we want, a continuous stream of silence that anything measuring time from the stream can count on. I can't prove after the fact that permissions played no part in that first failure (it was a command-line tool launched from Terminal, and I never re-ran it with auto-start off), but a denied tap turned out to look different anyway, as we'll see below. The empty include list I only found by reading the API, every probe run used the global tap.

So the version that works is:

let description = CATapDescription(stereoGlobalTapButExcludeProcesses: [ownProcessObject])
description.isPrivate = true
description.muteBehavior = .unmuted
AudioHardwareCreateProcessTap(description, &tapID)

let aggregate: [String: Any] = [
    kAudioAggregateDeviceNameKey: "System Audio",
    kAudioAggregateDeviceUIDKey: UUID().uuidString,
    kAudioAggregateDeviceMainSubDeviceKey: defaultOutputUID,
    kAudioAggregateDeviceIsPrivateKey: true,
    kAudioAggregateDeviceIsStackedKey: false,
    kAudioAggregateDeviceTapAutoStartKey: false,
    kAudioAggregateDeviceTapListKey: [[
        kAudioSubTapDriftCompensationKey: true,
        kAudioSubTapUIDKey: description.uuid.uuidString,
    ]],
]
// then create the aggregate, the IOProc and start it, as in the first version
Enter fullscreen mode Exit fullscreen mode

ownProcessObject comes from translating our PID with kAudioHardwarePropertyTranslatePIDToProcessObject, and defaultOutputUID is the kAudioDevicePropertyDeviceUID of the device that kAudioHardwarePropertyDefaultOutputDevice returns. In the probe the app played a system sound of its own during a silent run and every second still read -180 dBFS, so the exclusion works the way excludesCurrentProcessAudio does in ScreenCaptureKit. That also means that when you test a tap, the sound has to come from another process (afplay, a browser), or you'll be looking at zeros and wondering why. It ran under the App Sandbox with no extra entitlement, only NSAudioCaptureUsageDescription in the Info.plist and one "System Audio Recording" prompt the first time.

That prompt blocks inside AudioDeviceCreateIOProcIDWithBlock for as long as it's on screen (1.3 to 11 seconds in my runs), so create the IOProc off the main thread. A rebuilt dev-signed build also lost the grant when I reinstalled it, so expect the prompt again while developing. And since the IO block runs on the HAL's real-time thread, keep it free of allocations, locks and logging, and hand the samples off to something else.

Why ScreenCaptureKit wasn't good enough

ScreenCaptureKit did record audio fine, and for seven months I had no reason to doubt it. There's no audio-only stream in it, though, every SCStream carries video, so the code captured the first display at 2x2 pixels and 1 fps and threw the frames away.

The problem showed up when I added a banner that the app posts in the middle of a recording. It was posted and delivered, and it never appeared. NotificationCenter's log said muted by display state (displayShared), the app was listed under "Currently Sharing" in Control Center, and it wasn't only my banner, every app's notifications were muted for the whole recording, because macOS treated even that tiny display stream as screen sharing. The only way around it is a setting the user has to find themselves ("Allow notifications when mirroring or sharing the display"), which is a lot to ask from someone who just wants their meeting notes.

With the tap, a test banner posted during the probe showed up, the app didn't appear under Currently Sharing, and NotificationCenter resolved the notification the same way it does when nothing is capturing at all. The cost was moving the app's minimum OS from 14.0 to 14.2.

Smaller things the tap needed

Read the sample rate from the aggregate, not the tap. kAudioTapPropertyFormat said 48 kHz, but with Bluetooth headphones as the output the IO ran at 44.1 kHz. 12 seconds of frames divided by 48,000 came to 11.6 s against a 12.62 s host-time span, so trusting the tap's format would have made the audio about 8% too short and played it about 9% too fast. Divided by 44,100 they matched. So we read the aggregate's nominal sample rate (or the IOProc's input stream format), resample from that, and read it again when the device reports a rate change.

You don't need to rebuild the aggregate when the output changes. Since the main sub-device is pinned at creation, it's tempting to recreate the aggregate whenever the default output device changes, but measuring it first showed IO kept running at 93-108 callbacks a second across speakers to AirPods and back, with 155.20 s of audio against a 155.19 s host-time span, so the output-change listener only logs. (I couldn't get the Bluetooth hands-free profile to kick in, where the rate drops to 16 kHz or lower, so I can't say what happens there.)

Removing property listeners. In the probe, AudioObjectRemovePropertyListenerBlock didn't seem to remove anything, and events kept arriving after teardown. My best guess is that the Swift closure was bridged to a new block on each call, so the block passed to remove wasn't the one that was registered, but I never confirmed it. What works is AudioObjectAddPropertyListener with a C function and a fixed context pointer, which removes by the same function and pointer. Even then, nothing guarantees a notification that's already on its way stops at removal, so the teardown sets a "finished" flag on the context before removing the listeners, and never frees the context (it's a few small objects per recording, which is a fair price for not having a use-after-free).

A denied tap looks exactly like a silent Mac. After clicking Don't Allow, every call still returned 0, the device ran, callbacks came about 99 times a second with valid host times, and every buffer was exact zero, even with afplay playing something the same tap heard fine once access was granted. There's no public API to tell the two apart, so the app checks the grant with the private TCCAccessPreflight, which doesn't prompt and takes a few ms. It's a private symbol, so it isn't App Store safe and could go away, and I've only tested it on macOS 26. It also lags behind a fresh grant, after clicking Allow it keeps reading "not determined" until the app is relaunched. For those cases (and when the symbol is missing or returns something unexpected) the app plays a -90 dBFS tone through afplay and checks whether the tap hears any non-zero sample, and once it has heard one it remembers the grant until the app quits. -90 dBFS is about as quiet as a 16-bit sample gets, a much quieter tone (-120 dBFS in my test) written to a 16-bit file is just zeros, and the tap captures before the output volume and mute, so a -60 dBFS tone was still heard with the Mac muted and with the volume at 0. A command-line tool can only use the tone, because TCC attributes the tool's access to the terminal that launched it, so the tool's own preflight said "not determined" while its tap was capturing fine.

Summary

If a process tap returns noErr everywhere and the IOProc never fires, check kAudioAggregateDeviceTapAutoStartKey and which processes the CATapDescription includes before you go anywhere near TCC. A denied tap still runs and delivers zeros, while an auto-start aggregate with nothing to wake it doesn't run at all, so test with sound from another process and with nothing playing, and look at whether the device is running, not only at what's in the buffers. For recording system audio, a global tap that excludes your own process is a better tool than ScreenCaptureKit, which can't record audio without a video stream, and macOS treated even a 2x2 display stream as screen sharing.

Top comments (0)