AVAudioSession manipulate sound output

空扰寡人 提交于 2019-12-18 07:08:47

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/25133772/avaudiosession-manipulate-sound-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!