DEV Community

SleepTrace
SleepTrace

Posted on

Field notes: all-night audio recording on iOS without dying in the background

Keeping a microphone alive all night on iOS sounds trivial and is not. Some field notes from building an audio-first sleep tracker, for anyone fighting the same OS behaviors.

The problem

iOS suspends backgrounded apps aggressively. An AVAudioSession with the playAndRecord category keeps you alive - until the user locks the phone, another app grabs the session, or the system decides you are idle. Result: silent gaps in the night you only discover in the morning.

What actually works

  1. A keep-alive audio node. A muted output node on the audio graph signals "actively doing audio" to the OS. Without it, recording-only sessions get reaped on lock on some OS versions.
  2. Interruption handling as a state machine. Calls, alarms, Siri, CarPlay handoffs - each fires AVAudioSession.interruptionNotification with slightly different resume semantics. Treat resume as maybe: re-activate, verify input, and log the gap if re-activation fails.
  3. Watchdog timestamps. Write a heartbeat every N seconds. Morning-after, the gaps between heartbeats tell you exactly when and how long recording was dead - which is also honest UX: show the user the gap instead of pretending the night was complete.
  4. Battery discipline. Process in chunks, classify on-device, discard raw audio you do not need. A full night of raw PCM is storage and battery poison.

Why bother

Because the acoustic events - snoring patterns, breathing pauses, sleep talking - are the part of the night that motion sensors cannot see. The clinical background on why those sounds matter is summarized in this overview of snoring vs. sleep apnea.

Questions about the audio session details welcome - happy to share more specifics in the comments.

Top comments (0)