I'm working on iPad.
I would like to detect when user plug-out headphone. First I used a listener on the property kAudioSessionProperty_AudioRouteChange
. So all was working well until I've decided to add a button to switch to speakers when headphone was still plugged. So I’m now facing a problem, maybe someone would have an idea to fix it.
Here is the scenario :
- I plug a headphone -> my audio route change callback is called
- then I switch sound to speakers (without unplugging my headphone) -> audio route change callback is called
- then I unplug my headphone (when sound is still outputting to speakers) -> audio route change callback is NOT called, which seems logical.
But here is my problem ! So my question is : Do you see a way to detect that headphone was unplugged for this last case ?
Thanks for your help
EDIT :
Ok I found a workaround :
To detect whether or not headphones are plugged, I execute a test function all the times I need to know it (instead using a boolean), this might be less good for performances but it's working, here is my code for the ones who may need it :
//set back the default audio route
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_None;
AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride);
//check if this default audio route is Heaphone or Speaker
CFStringRef newAudioRoute;
UInt32 newAudioRouteSize = sizeof(newAudioRoute);
AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &newAudioRouteSize, &newAudioRoute);
NSString *newAudioRouteString = (__bridge NSString *)newAudioRoute;
CFRelease(newAudioRoute);
//if this default audio route is not Headphone, it means no headphone is plugged
if ([newAudioRouteString rangeOfString:@"Headphones"].location != NSNotFound){
NSLog(@"Earphone available");
return true;
}
else {
NSLog(@"No Earphone available");
return false;
}
Hope it will help someone !
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…