Improved the Capturing protocol in the Recording package target to capture interruptions and pause any active capture process.

This commit is contained in:
2026-07-04 15:19:26 +02:00
parent 6a0e7698a5
commit 1f1ac630f3
5 changed files with 211 additions and 17 deletions
@@ -4,24 +4,66 @@ import AVFoundation
///
/// The service records into a temporary `.m4a` file through an `AVAudioRecorder`, and returns the file's location when the recording stops.
/// The user's permission to record is requested before a recording starts and, on the platforms that require it, the shared audio session is
/// configured for recording while the capture is in progress.
/// configured for recording while the capture is in progress. When the system interrupts the session while a recording is in progress
/// because of a phone call or Siri, for example the service emits ``CapturingEvent/interrupted`` through ``events``.
@MainActor
public final class AudioCapturing: Capturing {
// MARK: Properties
/// The stream of events the service emits outside its method calls.
public let events: AsyncStream<CapturingEvent>
/// The continuation that feeds ``events``.
private let continuation: AsyncStream<CapturingEvent>.Continuation
/// The recorder that captures the audio from the microphone into a temporary file.
private var recorder: AVAudioRecorder?
#if os(iOS) || os(visionOS)
/// The task that observes the interruptions of the audio session while the service lives.
private var taskInterruptions: Task<Void, Never>?
#endif
// MARK: Initializers
/// Creates an audio recording service.
public init() {}
public init() {
(events, continuation) = AsyncStream.makeStream(of: CapturingEvent.self)
#if os(iOS) || os(visionOS)
taskInterruptions = Task { [weak self] in
let notifications = NotificationCenter.default.notifications(
named: AVAudioSession.interruptionNotification,
object: AVAudioSession.sharedInstance()
)
for await notification in notifications {
guard let self else {
return
}
self.handleInterruption(notification)
}
}
#endif
}
deinit {
#if os(iOS) || os(visionOS)
taskInterruptions?.cancel()
#endif
continuation.finish()
}
// MARK: Methods
/// Starts a new audio recording from the microphone.
///
/// On the platforms that require an audio session, the session is deactivated again when the recorder fails to start after
/// the session was activated.
///
/// - Throws: ``AudioCapturingError/permissionNotGranted`` when the user denies the app access to the microphone,
/// ``AudioCapturingError/captureNotStarted`` when the recorder fails to start, or any error thrown while configuring
/// the audio session or creating the recorder.
@@ -37,16 +79,24 @@ public final class AudioCapturing: Capturing {
try session.setActive(true)
#endif
let recorder = try AVAudioRecorder(
url: Constant.File.url,
settings: Constant.Audio.settings
)
do {
let recorder = try AVAudioRecorder(
url: Constant.File.url,
settings: Constant.Audio.settings
)
guard recorder.record() else {
throw AudioCapturingError.captureNotStarted
guard recorder.record() else {
throw AudioCapturingError.captureNotStarted
}
self.recorder = recorder
} catch {
#if os(iOS) || os(visionOS)
try? AVAudioSession.sharedInstance().setActive(false)
#endif
throw error
}
self.recorder = recorder
}
/// Pauses the ongoing recording.
@@ -95,6 +145,33 @@ public final class AudioCapturing: Capturing {
}
#if os(iOS) || os(visionOS)
// MARK: - Helpers
private extension AudioCapturing {
/// Handles an interruption notification of the audio session, emitting ``CapturingEvent/interrupted`` through ``events``
/// when the system began interrupting an ongoing recording. The end of an interruption is deliberately ignored: the capture is
/// never resumed without the user asking for it.
///
/// - Parameter notification: The interruption notification posted by the audio session.
func handleInterruption(
_ notification: Notification
) {
guard
recorder != nil,
let typeValue = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
AVAudioSession.InterruptionType(rawValue: typeValue) == .began
else {
return
}
continuation.yield(.interrupted)
}
}
#endif
// MARK: - Errors
/// The errors thrown by ``AudioCapturing``.