Skip to content

Instantly share code, notes, and snippets.

@dillon-mce
Last active February 6, 2024 15:39
Show Gist options
  • Save dillon-mce/5f0d03aa89900571a205897cbedda134 to your computer and use it in GitHub Desktop.
Save dillon-mce/5f0d03aa89900571a205897cbedda134 to your computer and use it in GitHub Desktop.
Handling Audio Route Changes
#import AVFoundation
// Observe the route change notification
NotificationCenter.default.addObserver(
self,
selector: #selector(handleRouteChange),
name: AVAudioSession.routeChangeNotification,
object: AVAudioSession.sharedInstance()
)
@objc private func handleRouteChange(_ notification: Notification) {
// pull the reason the route changed out of the notification
guard let info = notification.userInfo,
let rawReason = info[AVAudioSessionRouteChangeReasonKey] as? UInt else { return }
let reason = AVAudioSession.RouteChangeReason(rawValue: rawReason)
// if the reason is that the old device is no longer available
if reason == .oldDeviceUnavailable {
let previousRoute = info[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription
let portType = previousRoute?.outputs.first?.portType
// and that old device was headphones
if portType == .headphones {
// stop the audio that the user potentially wanted to keep private
stopPlayingAudio()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment