Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
979 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...