Sr.Richie
Sr.Richie

Reputation: 5740

Detect if headset is plugged in - iOS 5

I'm aware that this is a question already asked, I've found possible duplicates:

Detecting if headphones are plugged into iPhone

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

Detect if headphones (not microphone) are plugged in to an iOS device

...and more info on the WWW. But I've tried out every solution given and everytime I have problem, probably because they are old threads and are referring to iOS 4. How can I detect it on iOS 5.0? Thanks

Upvotes: 2

Views: 3344

Answers (2)

user3095716
user3095716

Reputation:

Wes seems to have a great solution. Alas it is not international-proof. This code only works for the English language. In Dutch, for instance, the headset is called 'Koptelefoon' and

    *portName 

contains indeed 'Koptelefoon' which makes the test fail.

This will do the job internationally correct:

    if ([portDescription.portType isEqualToString:AVAudioSessionPortHeadphones])
        ;

Upvotes: 4

Wes Dearborn
Wes Dearborn

Reputation: 366

If you're okay with an iOS 6-only solution, Apple added several new AVAudioSession properties that let you detect audio routes in just a few lines (and without the use of C).

Use this method to check for headphones (or adjust it to check for other outputs - "Speaker", "Headset", etc.):

- (BOOL)isHeadsetPluggedIn
{
    // Get array of current audio outputs (there should only be one)
    NSArray *outputs = [[AVAudioSession sharedInstance] currentRoute].outputs;

    NSString *portName = [[outputs objectAtIndex:0] portName];

    if ([portName isEqualToString:@"Headphones"]) {
        return YES;
    }

    return NO;
}

If you want to respond to audio route changes passively, you can do this with the new NSNotification, AVAudioSessionRouteChangeNotification. Unfortunately, this notification doesn't tell you what the new route is, just the previous route that it switched from. But, you can just call some variation of the method above to get the current route.

Upvotes: 9

Related Questions