How to switch between speaker and headphone in iPhone app

I wrote an application that plays audio using AVAudioPlayer.

I implemented a function that switches the sound to the speaker:

UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback; AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory); UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker; AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride); 

But when I try to switch it back to the headphones using this:

 UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback; AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory); UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_None; AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride); 

he remains directed through the speaker.

I can not find another way to control audio. Can anyone suggest what I'm doing wrong?

+4
source share
2 answers

According to Apple's documentation , rerouting audio session routes is only available when using the kAudioSessionCategory_PlayAndRecord category.

You can try changing the category to kAudioSessionCategory_PlayAndRecord and use the kAudioSessionProperty_OverrideCategoryDefaultToSpeaker property kAudioSessionProperty_OverrideCategoryDefaultToSpeaker to route the sound to the speaker.

+4
source

As Laurent said, try using PlayAndRecord like this:

 [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil]; UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker; AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride); 

It is very important to use AVAudioSessionCategoryPlayAndRecord , or the route will not go to the speaker. After you set the redefinition route for the audio session, you can use an instance of AVAudioPlayer and send some output to the speaker.

Hope this works for others, as it was for me. The documentation on this subject is scattered, but the Skype application proves this. Go on, my friends! :)

Some Apple documentation here: http://developer.apple.com/library/ios/#documentation/AudioToolbox/Reference/AudioSessionServicesReference/Reference/reference.html

Do a search on kAudioSessionProperty_OverrideAudioRoute

0
source

Source: https://habr.com/ru/post/1307273/


All Articles