I have an audio player which has an option of switching the Audio Output from Speaker to Receiver/Earpiece (irrespective of whether headset is connected) when proximity sensor notifies 1. The following is my code for doing so.
- (void) switchAudioOutput:(NSString*)output{
AVAudioSession* audioSession = [AVAudioSession sharedInstance];
BOOL success;
NSError* error;
if([output isEqualToString:keAudioOutputReciever]){
//Force current audio out through reciever
//set the audioSession override
success = [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideNone
error:&error];
if (!success)
NSLog(@"AVAudioSession error overrideOutputAudioPort:%@",error);
//activate the audio session
success = [audioSession setActive:YES error:&error];
if (!success)
NSLog(@"AVAudioSession error activating: %@",error);
else
NSLog(@"AVAudioSession active with override: AVAudioSessionPortOverrideNone");
}else if([output isEqualToString:keAudioOutputSpeaker]){
//set the audioSession override
success = [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker
error:&error];
if (!success)
NSLog(@"AVAudioSession error overrideOutputAudioPort:%@",error);
//activate the audio session
success = [audioSession setActive:YES error:&error];
if (!success)
NSLog(@"AVAudioSession error activating: %@",error);
else
NSLog(@"AVAudioSession active with override: AVAudioSessionPortOverrideSpeaker");
}
}
This was based on the answer Toggle Button route audio to speaker and receiver and enter link description here. I noticed that this only forces the Audio to Speaker alone but does not ensure that the route goes to receiver alone. Moreover while shifting to speaker I get the following error:
AVAudioSession error overrideOutputAudioPort:Error Domain=NSOSStatusErrorDomain Code=-50 "The operation couldn’t be completed. (OSStatus error -50.)"