ClamNotes records a lesson, transcribes it on the device and writes a study note at the end. The recording has to survive the whole lesson: the screen locks, the student checks a message, a call comes in, AirPods connect, an iPad's cover closes. My first version handled the textbook cases. Then in October 2026 an iPad and an iPhone both showed a recording clock running over a microphone that had stopped listening. This is what I learned fixing it, checked against Apple's documentation where Apple documents it, and marked as my own observation where it doesn't.
The naive version
Why AVAudioEngine and not AVAudioRecorder: the audio never touches the disk. A tap on the input node hands buffers to an AVAudioConverter, which turns them into 16 kHz mono floats for the speech model, in memory. Here is the recorder as it was on 28 September 2026. It is roughly what every tutorial shows, and it works in a demo.
// The first version, trimmed
func start() throws {
let session = AVAudioSession.sharedInstance()
try session.setCategory(.record, mode: .spokenAudio, options: [])
try session.setActive(true)
try open() // a new AVAudioEngine, a tap on inputNode, engine.start()
// interruptionNotification: .began closes the engine, .ended calls reopen()
// mediaServicesWereResetNotification and AVAudioEngineConfigurationChange call reopen()
}
private func reopen() {
guard isRunning else { return }
close()
do {
try AVAudioSession.sharedInstance().setActive(true)
try open()
} catch {
stop()
onInterrupted?(error)
}
}
Nearly every line was wrong somewhere. The mode is refused outright. reopen() reactivates the session, the step that fails in the background. A failed reopen ends the recording, right when the person is watching and wrong when the phone is in a pocket. And nothing notices an engine that stops without telling anyone, which is what actually cost me recordings.
The session: category, mode and options
The category is .record. Its documentation says the two things you need: add audio to UIBackgroundModes to keep recording when the screen locks, and the category does not stop calls, alarms or other non-mixable sessions from interrupting you.
The mode was my first wrong turn. .spokenAudio sounds right for recording a lecture, but it is a playback mode: the SDK header describes it as being for apps "which play spoken audio", podcast players and audiobooks. With .record, setCategory threw error -50 (AVAudioSessionErrorCodeBadParam). The mode is .default now.
// simplified
private func activate() throws {
let session = AVAudioSession.sharedInstance()
var refused: Error?
if !Self.refusesMutedOverride {
do {
try session.setCategory(.record, mode: .default,
options: [.allowBluetoothHFP, .overrideMutedMicrophoneInterruption])
try session.setActive(true)
preferBuiltInMicrophone(session)
return
} catch {
refused = error
}
}
try session.setCategory(.record, mode: .default, options: [.allowBluetoothHFP])
try session.setActive(true)
// It was the option, not the microphone being taken: without it until the app restarts.
if refused != nil { Self.refusesMutedOverride = true }
preferBuiltInMicrophone(session)
}
Three details in there:
.allowBluetoothHFPis the current name;.allowBluetoothis deprecated in the iOS 26 SDK with this as its replacement. It is only valid with.recordand.playAndRecord..overrideMutedMicrophoneInterruption(iOS 14.5) changes what happens when an iPad's cover is closed and the built-in microphone is cut off in hardware. By default the system interrupts your session. With the option, the session stays active and the microphone keeps producing buffers in which every sample is 0 (documentation). Apple documents it for categories that do both input and output, such as.playAndRecord, so I try it with.recordand fall back without it if the system refuses. I haven't yet seen on a device which of the two paths iOS takes; the fallback is there so that it doesn't matter.preferBuiltInMicrophonecallssetPreferredInputwith the built-in microphone, so a student wearing AirPods doesn't record narrow-band call audio from their own ear. A wired or USB microphone wins over both.
Background mode keeps you alive only while audio flows
I had this backwards. When I added a Pause button on 30 September, my comment said the session "stays active, so the app keeps running in the background". It doesn't. The audio background mode keeps the app alive while it is actually recording or playing; a stopped engine on an active session is neither, and iOS may suspend you. Since 11 October, any pause first writes down what was heard so far.
The bigger problem came on 13 October: an iPad and an iPhone on iOS 27 recorded nothing in the background. My watchdog reopened the microphone after two seconds without a buffer, and it never ran. My diagnosis: when the microphone stops in the background, iOS suspends the app within a few seconds, before the watchdog's turn. The Lock Screen clock kept moving because the system draws it from a start date.
The fix is to hold background time for the entire time the recording runs in the background:
/// Held the whole while the recording runs in the background. iOS doesn't count it down while
/// the microphone keeps the app running; once the microphone stops, it keeps the app from
/// being suspended long enough for the recovery to open it again.
private var keepTime = UIBackgroundTaskIdentifier.invalid
private func beginKeepTime() {
guard keepTime == .invalid else { return }
var task = UIBackgroundTaskIdentifier.invalid
task = UIApplication.shared.beginBackgroundTask(withName: "Recording") { [weak self] in
// iOS is about to suspend the app. The recovery usually acted ten seconds before,
// as little started from here gets to finish.
Self.onMain {
guard let self else { return }
self.feed(.backgroundTimeExpired)
// iOS ends an app that keeps an expired task.
if self.keepTime == task { self.endKeepTime() }
}
}
keepTime = task
}
/// A new one before the old one ends, so the app is never without.
private func renewKeepTime() {
let old = keepTime
keepTime = .invalid
beginKeepTime()
if old != .invalid { UIApplication.shared.endBackgroundTask(old) }
}
It is taken in didEnterBackground, ended in willEnterForeground, and renewed after every successful reopen so each stall starts with a full allowance. The comment in the code is my working assumption: the allowance doesn't run down while the microphone keeps the app alive, only once it stops. I haven't measured that on a locked phone, so nothing depends on how long the allowance is: the watchdog reopens after two seconds, and the recovery gives up cleanly with ten seconds left.
One more trick: when the first reopen in the background fails, the notification is scheduled twenty seconds ahead with a UNTimeIntervalNotificationTrigger and removed if the reopen works. If iOS suspends the app first, the notification is already in the system's hands. Not for a reopen that works at once, though: a request and its removal milliseconds apart can reach iOS in either order.
Rebuild the engine, not the session
AVAudioEngine has its own notification, AVAudioEngineConfigurationChange. Apple's description: when the engine's I/O unit sees the hardware's channel count or sample rate change, the engine stops itself, uninitializes, and posts it. The nodes stay connected with the old formats (documentation). For an input tap, the format you installed it with is now wrong. So I build a new engine every time the microphone opens; one kept around holds on to the format of the input it first opened.
The first version also called setActive(true) before every reopen. In the background on iOS 27 that activation failed where a new engine on the session as it was worked. iOS is strict about recording that starts in the background: the SDK's AVAudioSessionErrorCodeCannotStartRecording ('!rec', error 561145187, the one in a long-running forum thread) is documented as "usually because it is starting a mixable recording from the background". So in the background the reopen first builds a new engine on the existing session, and only activates the session if that fails (after a media services reset, for example, the session really is gone):
private func openAgain() throws {
close()
if Self.inBackground {
do {
try open() // a new engine on the session as it is
return
} catch {
close() // fall through: activate, then open
}
}
try activate()
try open()
}
private func close() {
if let engineObserver { NotificationCenter.default.removeObserver(engineObserver) }
engineObserver = nil
guard let old = engine else { return }
old.inputNode.removeTap(onBus: 0)
old.stop()
engine = nil
// Let go of it a moment later: an engine freed inside its own configuration
// change's handler can deadlock.
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { withExtendedLifetime(old) {} }
}
The delayed release follows Apple's note on the configuration change: don't deallocate the engine inside the handler, as synchronous teardown can deadlock.
Route changes (routeChangeNotification arrives on a secondary thread, so observe with queue: .main) are logged, and reopen the microphone only if the engine stopped.
Interruptions on iOS 26 and iOS 27
Up to iOS 26 there is one notification, AVAudioSession.interruptionNotification, with a .began and an .ended, the latter carrying a .shouldResume option. In iOS 27 InterruptionType, InterruptionOptions and their keys are deprecated in favour of three lifecycle notifications: didBecomeActiveNotification, didBecomeInactiveNotification (with a DeactivationContext whose source is .app or .system, and an interruptionContext when the system did it) and resumptionRecommendationNotification (a ResumptionContext whose recommendation is .shouldResume or .shouldNotResume). Apple's article on interruptions says why: they "don't get out of sync when the system can't deliver an end event".
That matches what I saw: an interruption that began during the person's pause never got an end. So "ended" is a hint. In front, a recording paused for another app is retried every five seconds while isOtherAudioPlaying is false, and coming back to the app retries too.
// simplified: the iOS 27 observers, added next to the legacy interruptionNotification
if #available(iOS 27.0, *) {
center.addObserver(forName: AVAudioSession.didBecomeInactiveNotification,
object: session, queue: .main) { [weak self] note in
guard let self, isRunning else { return }
let context = note.userInfo?[AVAudioSession.deactivationContextKey]
as? AVAudioSession.DeactivationContext
guard context?.source != .app else { return } // our own, at Stop
if let reason = context?.interruptionContext?.reason {
feed(.interruptionBegan(mutedMicrophone: reason == .builtInMicMuted))
} else {
// Deactivated while the app was suspended, and told only now.
feed(.deactivatedWhileSuspended)
}
}
center.addObserver(forName: AVAudioSession.resumptionRecommendationNotification,
object: session, queue: .main) { [weak self] note in
let context = note.userInfo?[AVAudioSession.resumptionContextKey]
as? AVAudioSession.ResumptionContext
self?.feed(.interruptionEnded(shouldResume: context?.recommendation != .shouldNotResume))
}
}
On iOS 27 the deprecated notification still arrives, so a call produces a legacy .began and a deactivation. The state machine takes the second as a repeat, and told not to resume, the recording stays paused and asks for the app in the background. A deactivation with no interruption context is an old behaviour Apple documents on interruptionNotification: the system deactivates a suspended app's session and can only say so once it runs again. Nobody else holds the microphone then, so it reopens at once.
An open microphone that hears nothing
On 12 October an iPad came back to a clock still running and no sound. No interruption, no configuration change, no error: the engine had stopped and nothing in my code noticed. The other quiet failure is worse: the installTap block keeps firing at the normal rate, with a valid format and no error, and every buffer is all zeros. It shows up in the developer forums as an input tap that intermittently delivers all-zero buffers, with no reply yet. Two checks now run every second on the main run loop (in .common mode, so scrolling doesn't pause them):
- No buffer for two seconds, or
engine.isRunningfalse: reopen. Those seconds are reported as a gap and left out of the clock, so clock and transcript agree. - Buffers arrive, but every sample is exactly 0.0 for five seconds: reopen once (at most once a minute). Still zeros after that: show the recording as paused (muted) and drop zero buffers until a real sample returns.
The test is literal, not a loudness threshold: a real microphone in a quiet room still produces noise, so exact zeros mean the system muted it. That happens with an iPad's cover closed and the override option above, with a MacBook's lid closed (Apple's hardware microphone disconnect covers both), and iPhone Mirroring with the phone locked does it too (the forum thread above reproduces it that way).
// simplified: after converting the tap's buffer to 16 kHz mono
lastBuffer.withLock { $0 = .now }
let heard = samples.contains { $0 != 0 }
if heard { lastSound.withLock { $0 = .now } }
// Paused for zeros: they stay out of the pieces until it hears again.
if !heard, mutedNow.withLock({ $0 }) { return }
onSamples?(samples)
A third rule came from an audit: an engine can start, report isRunning, and never deliver a buffer. The old code reopened it every three seconds forever. Now three such opens in a row count as a failed reopen, and the recording pauses until a retry delivers. On an iPhone 11, a silent engine stop with the app in front recovered in one second.
The state machine
By the evening of 13 October the recovery logic was spread across notification handlers, a timer, background task callbacks and the capture thread, and the hard part was the interactions between them. For build 0.7 (12) I moved every decision into MicrophoneRecovery, a value type that imports only Foundation. The capture class tells it what happened (an Event) and what it sees (a Moment: last buffer, last non-zero buffer, engine running, background, time left), and carries out the Actions it answers with.
/// Tells the recovery, and does what it says; an open's outcome goes back to it at once.
private func feed(_ event: MicrophoneRecovery.Event) {
var queue = recovery.handle(event, moment())
while !queue.isEmpty {
let action = queue.removeFirst()
if let answer = perform(action) { // only .open answers: .opened or .openFailed
queue = recovery.handle(answer, moment()) + queue
}
}
}
// The actions, from MicrophoneRecovery:
// .open, .close, .deactivate, .retry(after:turn:), .pause(PauseReason?), .gap(TimeInterval),
// .beginKeepTime, .endKeepTime, .renewKeepTime, .beginReopenTime, .endReopenTime,
// .notice(.ahead(20) | .now | .withdraw), .fail, .log
Every pause carries a reason the person sees on the recorder and the Lock Screen. Here is the whole machine, without the person's own Pause button, which sits outside these rules until Resume.
| # | Transition | When |
|---|---|---|
| 1 | Recording → Reopening | No buffer for 2 s, the engine stopped without a word, a configuration change, a media services reset, a route change that stopped the engine, leaving the app with a quiet microphone, or zeros for 5 s (at most once a minute). |
| 2 | Reopening → Recording | The new engine started. After three opens that delivered nothing, only once a buffer arrives. |
| 3 | Recording → Muted | Still only zeros after the reopen. |
| 4 | Muted → Recording | A buffer with anything but zeros. |
| 5 | Recording → Other app | A call, Siri or another app took the session: .began, or an iOS 27 deactivation by the system. A cover that interrupts (reason builtInMicMuted) pauses the same way but shows as muted. |
| 6 | Other app → Reopening | The interruption ended with a recommendation to resume, the app came back, or 5 s passed in front with no other audio playing. |
| 7 | Reopening → Unavailable | On a Mac, the first try and the retries after 0.5, 1 and 2 s all failed. On any device, three opens in a row delivered nothing. (After a call the pause stays Other app.) |
| 8 | Unavailable → Reopening | Every 5 s, when the app comes back, and on a Mac when the default input changes. |
| 9 | Reopening → Stopped | All four tries failed in front on an iPhone. The person sees it and can start again; the note is written from what was heard. |
| 10 | Reopening → Needs the app | The tries failed in the background. The notification is shown at once. |
| 11 | Needs the app → Reopening | The person opened ClamNotes. |
| 12 | Other app → Needs the app | In the background, iOS 27 recommends not resuming, or a cover-muted microphone has under 10 s of background time left. |
| 13 | Unavailable → Needs the app | Under 10 s of background time left and nothing delivered. The same rule applies to a stalled reopen. |
Because the machine is pure, its tests need no device. They simulate a microphone and a clock: each tick is a second, buffers carry sound, zeros or nothing, and each .open succeeds or fails as the test says. There is one test per rule and per incident, plus one that replays 200 seeded random sequences of up to 150 events, for both the iPhone and the Mac policy, checking the invariant after every event:
// from testTheMicrophoneIsNeverClosedWhileTheClockCountsOn, trimmed
let m = mic.machine
guard m.running, !m.held else { continue }
XCTAssertTrue(m.open || m.retryPending || m.pause != nil,
"closed with nothing under way after \(event)")
XCTAssertEqual(m.shown, m.pause, "the pause shown is the pause")
if m.needsApp { XCTAssertEqual(m.pause, .needsApp) }
One detail worth stealing: every reopen, pause, interruption or Stop increments a "turn", and a retry scheduled with asyncAfter carries its turn. If anything happened in between, it is dropped. Otherwise a retry scheduled just before a call would try to take the microphone back from the call.
The Mac side
The Mac app shares the capture class and the state machine. There is no AVAudioSession on macOS and nothing gets suspended, so no interruptions and no background time. A Mac often records with nobody at it, so a microphone that won't reopen pauses and retries every five seconds instead of ending the recording (keepsTrying). What the Mac has instead is input devices that come and go, so the default input gets a Core Audio listener, a burst of changes coalesced into one event:
// simplified
var address = AudioObjectPropertyAddress(mSelector: kAudioHardwarePropertyDefaultInputDevice,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: kAudioObjectPropertyElementMain)
var pending: DispatchWorkItem?
let listener: AudioObjectPropertyListenerBlock = { _, _ in
pending?.cancel()
let work = DispatchWorkItem { MainActor.assumeIsolated { changed() } }
pending = work
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: work)
}
AudioObjectAddPropertyListenerBlock(AudioObjectID(kAudioObjectSystemObject), &address, .main, listener)
Each new engine is then bound to a chosen device with engine.inputNode.auAudioUnit.setDeviceID(_:) before its input format is read. As on the iPhone, the built-in microphone wins over AirPods. With the lid closed, which disconnects it in hardware, another real input wins if there is one: USB, Thunderbolt, a display's, Continuity, then Bluetooth. The closed lid comes from the AppleClamshellState property of IOPMrootDomain, which is undocumented, so an unreadable value counts as open.
While recording, the app holds a ProcessInfo activity with .idleSystemSleepDisabled and .latencyCritical. Closing the lid or choosing Sleep still sleeps the Mac, and that time comes out of the clock, measured with two Swift clocks:
/// Time the Mac slept: the continuous clock counts on while it sleeps, the suspending one doesn't.
struct SleepMeter {
private var continuous = ContinuousClock.now
private var suspending = SuspendingClock.now
mutating func slept() -> Duration {
let (nowContinuous, nowSuspending) = (ContinuousClock.now, SuspendingClock.now)
defer { (continuous, suspending) = (nowContinuous, nowSuspending) }
return (nowContinuous - continuous) - (nowSuspending - suspending)
}
}
The machine reports any sleep over a second as a gap, the same action a stall produces on the iPhone.
Testing it without a hand on the phone
All of this happens with the screen locked, where you can't watch, and devicectl can't lock a device. Two things helped. First, fault injection through launch arguments in Debug builds: -ClamNotesDebugRecord YES starts a recording by itself, and -ClamNotesDebugMicFault stop|zeros|refuse with -ClamNotesDebugMicFaultAfter and -ClamNotesDebugMicFaultFor does to the microphone, after a delay, what iOS did to it in the field: stops the engine silently, makes it deliver zeros, or refuses every reopen for a while (sixty seconds by default, long enough for the background time to run out). Start it, lock the phone, wait, read the log.
Second, a Debug-only log file, written when the app is left, comes back, a recording stops and every two minutes, copied off the device with devicectl. It records what happened to the microphone (interruption and route change reasons, port types, error codes), never what it heard or a device's name.
The unit tests and the fault injection with the phone in front are verified. The real lock-screen run needs a finger on the side button, and it is the one part of this post I haven't seen with my own eyes yet.
Takeaways
The audio background mode is a promise for exactly as long as audio flows, so plan for the moment it stops: background time held in advance, action taken with ten seconds left rather than in the expiration handler. Treat AVAudioEngine as disposable, and treat notifications as hints, because engines stop and interruptions end without one, and a muted microphone delivers perfectly valid buffers of zeros. A one-second watchdog that looks at the buffers themselves catches what the notifications miss. Above all, never let the clock count over a closed microphone: it is open, it is being opened, or the person sees a pause and why. Put that rule in a pure type and let a random event generator try to break it.
Built for ClamNotes
This recorder is what keeps a whole lesson in ClamNotes, phone locked in a bag.
ClamNotes records a class, transcribes it on the device and writes a study note in the language that was spoken. For iPhone, iPad and Mac.
See ClamNotes