Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
976 views
in Technique[技术] by (71.8m points)

ios - AVAudioSession manipulate sound output

I'm using AVSoundSession to configure sound, and AVAudioPlayer 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 SoundManager where I could switch output between phone speaker and loudspeaker.

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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");

With

[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];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...