I have an app which does listen and play sound at the same time. By default, the sound output goes through the earphone. So I use the following code to route it through the speaker:
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride);
This works fine. But now, I'd like to route the sound through the headphones when headphones or external speakers are attached. How would I achieve that?
Also ideally all other sound (i.e. music etc.) should mute when the app launches.
Thanks!
To do this you have to add property listener when you setup audio session:
AudioSessionAddPropertyListener(kAudioSessionProperty_AudioRouteChange, audioSessionPropertyListener, nil);
Where
void audioSessionPropertyListener(void* inClientData, AudioSessionPropertyID inID,
UInt32 inDataSize, const void* inData) {
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
if (!isHeadsetPluggedIn())
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
}
BOOL isHeadsetPluggedIn() {
UInt32 routeSize = sizeof (CFStringRef);
CFStringRef route;
OSStatus error = AudioSessionGetProperty (kAudioSessionProperty_AudioRoute,
&routeSize,
&route
);
if (!error && (route != NULL) && ([(NSString*)route rangeOfString:@"Head"].location != NSNotFound)) {
NSLog(@"HeadsetPluggedIn");
return YES;
}
NSLog(@"Headset_NOT_PluggedIn");
return NO;
}
So when headphones are plugged in or out you get a notification and change audio output direction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With