Last active
February 6, 2024 15:39
-
-
Save dillon-mce/5f0d03aa89900571a205897cbedda134 to your computer and use it in GitHub Desktop.
Handling Audio Route Changes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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