Yevgen THD Yevgen THD - 1 year ago 130
iOS Question

AVAudioSession manipulate sound output

I'm using

to configure sound, and
to play different sounds.
I searched a lot and couldn't find anything. How can I manipulate output sources?

I need a method in my
where I could switch output between phone speaker and loudspeaker.

success = [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker

Using this I can route sound to loudspeaker, but there is no method to move it to phone speaker. Can anybody help me with it?

Answer Source

So, I found solution for manipulating with sound output.

You could initialize sound settings with AVAudioSession

Something like this:

session = [AVAudioSession sharedInstance];

BOOL success;
NSError* error;

success = [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];

if (!success)  NSLog(@"AVAudioSession error setting category:%@",error);
success = [session setMode:AVAudioSessionModeVoiceChat error:&error];

if (!success)  NSLog(@"AVAudioSession error setting mode:%@",error);

success = [session overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:&error];

[session setPreferredOutputNumberOfChannels:0 error:nil];
if (!success)  NSLog(@"AVAudioSession error overrideOutputAudioPort:%@",error);

success = [session setActive:YES error:&error];
if (!success) NSLog(@"AVAudioSession error activating: %@",error);
else NSLog(@"audioSession active");


[session overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:&error];

You set don't override output port. And your app playing with default speaker. As I understand for mode AVAudioSessionModeVoiceChat used phone speaker. It's directly what I need for my SIP caller app.

Then you can override output port with

[session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error];

I do it so:

- (void) loudSpeakerOn:(BOOL)isLoudSpeaker{
    [session setActive:NO error:nil];

    BOOL success;
    NSError* error;

    success = [session overrideOutputAudioPort:isLoudSpeaker?AVAudioSessionPortOverrideSpeaker:AVAudioSessionPortOverrideNone error:&error];

    if (!success)  NSLog(@"AVAudioSession error setting category:%@",error);

    [session setActive:YES error:nil];