Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
938 views
in Technique[技术] by (71.8m points)

objective c - headphone plug-in plug-out event when audio route doesn't change - iOS

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...