I have an audio player that has the ability to switch the audio output from the speaker to the receiver / headphone (regardless of whether a headset is connected) when the proximity sensor notifies you. Below is my code for this.
- (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 response of the Toggle Button for routing sound to the speaker and receiver and enter the link description here . I noticed that this only disables Audio to Speaker, but does not guarantee that the route will be sent only to the receiver. Moreover, when switching to the speaker, I get the following error:
Error AVAudioSession overrideOutputAudioPort: Error Domain = NSOSStatusErrorDomain Code = -50 "Operation could not be completed (error OSStatus -50.)"
source share