To listen to the route change events of AvAudioSession use the following observer.
let notificationCenter = NotificationCenter.default
notificationCenter.removeObserver(self)
notificationCenter.addObserver(self,
selector: #selector(routeChangeEventHandle),
name: AVAudioSession.routeChangeNotification,
object: nil)
Now add the handler used in the #selector:
@objc func routeChangeEventHandle(notification: Notification) {
guard let userInfo = notification.userInfo,
let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,
let reason = AVAudioSession.RouteChangeReason(rawValue: reasonValue) else {
print("Interrupption not reason.");
return
}
// Switch over the route change reason.
switch reason {
case .newDeviceAvailable: // New device found.
print("RouteChangeReason: New Device found.");
case .oldDeviceUnavailable: // Old device removed.
print("RouteChangeReason: Old device unavailable.");
case .categoryChange:
let session = AVAudioSession.sharedInstance();
print("session info:")
print(session.currentRoute.debugDescription);
print(session.category);
print(session.currentRoute);
print(session.mode);
print(session.categoryOptions);
print("RouteChangeReason: Category of av audio session has changed");
case .override:
print("RouteChangeReason: Category was overriden");
case .wakeFromSleep:
print("RouteChangeReason: Wake from sleep");
case .noSuitableRouteForCategory:
print ("RouteChangeReason: No suitable route for category");
case .routeConfigurationChange:
print ("RouteChangeReason: route configuration has been changed");
default:
print("RouteChangeReason: Unknown");
}
}
Cheers and Peace out.