Audio Output for Calls (iOS)
To enable seamless audio output switching within your application, you'll want to integrate Apple's robust CallKit framework. CallKit empowers your app to manage call services efficiently, ensuring a smooth user experience. Please refer to Apple's official documentation on CallKit here.
Integrating CallKit
For comprehensive guidance on integrating CallKit into your project and harnessing its full potential, please refer to Push notifications.
Current Audio Output Routes
To retrieve the currently available audio output sources, you can utilize AVAudioSession's currentRoute.outputs property. This will provide you with a list of all possible output sources at the moment.
let outputs = AVAudioSession.sharedInstance().currentRoute.outputs
outputs.forEach { audioSource in
switch audioSource.portType {
case .headphones:
print("headphones are used")
case .bluetoothA2DP:
print("Bluetooth audio is connected")
case .builtInSpeaker:
print("speaker is used")
case .builtInReceiver:
print("earpiece is used")
default:
print("other output: \(audioSource.portType.rawValue)")
}
}
You can also override the audio output source using the following code snippet:
// highlight-next-line
AVAudioSession.sharedInstance().overrideOutputAudioPort(.speaker)
We recommend avoiding setting or overriding audio settings via CallKit for a better experience.
Observing Audio Output Changes
You can subscribe to the AVAudioSession.routeChangeNotification notification to observe changes in the audio output. Here's how you can do it:
var cancelable: AnyCancellable?
func observeAudioRouteChanges() {
self.cancelable = NotificationCenter.default.publisher(for: AVAudioSession.routeChangeNotification).sink { notification in
/// process notification's user Info, to get audio change information
}
}
func removeAudioRouteChangesObserver() {
cancelable?.cancel()
}