问题
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 !
回答1:
I imagine a solution it in the following way:
You create in the AppDelegate a boolean for the speakers, let's say:
BOOL isSpeakerOn
. And every time the audio route callback is called you have to verify what the current situation with the speakers and what you want to do then.
回答2:
This is the best tutorial dealing this issue:
http://www.techotopia.com/index.php/Detecting_when_an_iPhone_Headphone_or_Docking_Connector_is_Unplugged_(iOS_4)
来源:https://stackoverflow.com/questions/10427239/headphone-plug-in-plug-out-event-when-audio-route-doesnt-change-ios