Audio Enroute Doesn't change to Speaker, Bluetooth Device, Mute or internal Speaker
Hi Devs,
i am struggling on a task where i need to switch the audio routing to various mediums such as bottom Speaker, Top speaker, Mute the Audio or a bluetooth Device connected such as Airpods or Car Audio.
I have using twilio to perform Video call across iPhone devices.
below code for setting up the session:
let audioSession = AVAudioSession.sharedInstance()
try audioSession.setCategory(.playAndRecord, mode: .voiceChat, options: [.defaultToSpeaker, .mixWithOthers, .allowBluetooth, .allowAirPlay, .allowBluetoothA2DP])
try audioSession.setActive(true)
Changing the Audio enroute using below function:
class func setAudioMode(as mode: AudioMode) {
switch mode {
case .speaker:
do {
print("Jatin Garg: Setting as Speaker")
try audioSession.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker)
} catch let error {
print("Jatin Garg : audioSession error turning on speaker: \(error.localizedDescription)")
}
case .mute:
do {
print("Jatin Garg: Setting as None")
try audioSession.setPreferredInput(.none)
try audioSession.overrideOutputAudioPort(AVAudioSession.PortOverride.none)
} catch let error {
print("Jatin Garg : audioSession error turning on None: \(error.localizedDescription)")
}
case .bleSpeaker:
let inputs = audioSession.availableInputs
print("jatin garg: inputs: \(String(describing: audioSession.availableInputs))")
for input in inputs ?? [] {
if input.portType.rawValue == AVAudioSession.Port.bluetoothA2DP.rawValue || input.portType.rawValue == AVAudioSession.Port.bluetoothHFP.rawValue ||
input.portType.rawValue == AVAudioSession.Port.bluetoothLE.rawValue ||
input.portType.rawValue == AVAudioSession.Port.headphones.rawValue ||
input.portType.rawValue == AVAudioSession.Port.carAudio.rawValue ||
input.portType.rawValue == AVAudioSession.Port.headsetMic.rawValue {
do {
print("Jatin Garg: Setting as BLE Speaker")
DefaultAudioDevice.DefaultAVAudioSessionConfigurationBlock()
try audioSession.overrideOutputAudioPort(AVAudioSession.PortOverride.none)
try audioSession.setPreferredInput(input)
} catch let error {
print("Jatin garg: Setting BLE Speaker Port: \(error.localizedDescription)")
setAudioMode(as: .speaker)
}
}
}
default:
let inputs = audioSession.availableInputs
print("jatin garg: inputs: \(String(describing: audioSession.availableInputs))")
for input in inputs ?? [] {
if input.portType.rawValue == AVAudioSession.Port.builtInMic.rawValue ||
input.portType.rawValue == AVAudioSession.Port.builtInReceiver.rawValue {
do {
print("Jatin Garg: Setting as built in mic")
try audioSession.setPreferredInput(input)
try audioSession.overrideOutputAudioPort(AVAudioSession.PortOverride.none)
} catch let error {
print("Jatin Garg : audioSession error turning on None: \(error.localizedDescription)")
}
}
}
}
}
Please help me what i am missing?
iPhone 11, iOS 15