Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

iphone

ipad

I need to change my audio depending on whether or not headphones are plugged in. I'm aware of kAudioSessionProperty_AudioInputAvailable, which will tell me if there's a microphone, but I'd like to test for any headphones, not just headphones with a built-in microphone. Is this possible?

like image 762
morgancodes Avatar asked Sep 16 '10 16:09

morgancodes


People also ask

Why does my iPhone not recognize my headphones?

Check for debris in the headphone port on your iPhone, iPad or iPod touch. Check your headphone cable, connector, remote, and earbuds for damage, like wear or breakage. Look for debris on the meshes in each earbud. To remove debris, gently brush all openings with a small, soft-bristled brush that's clean and dry.

Why is my earphone mic not detected?

Try the following solutions: If your headset has a Mute button, make sure it isn't active. Make sure that your microphone or headset is connected correctly to your computer. Make sure that your microphone or headset is the system default recording device.


2 Answers

Here is a method of my own which is a slightly modified version of one found on this site : http://www.iphonedevsdk.com/forum/iphone-sdk-development/9982-play-record-same-time.html

- (BOOL)isHeadsetPluggedIn {
    UInt32 routeSize = sizeof (CFStringRef);
    CFStringRef route;

    OSStatus error = AudioSessionGetProperty (kAudioSessionProperty_AudioRoute,
                                              &routeSize,
                                              &route);

    /* Known values of route:
     * "Headset"
     * "Headphone"
     * "Speaker"
     * "SpeakerAndMicrophone"
     * "HeadphonesAndMicrophone"
     * "HeadsetInOut"
     * "ReceiverAndMicrophone"
     * "Lineout"
     */

    if (!error && (route != NULL)) {

        NSString* routeStr = (NSString*)route;

        NSRange headphoneRange = [routeStr rangeOfString : @"Head"];

        if (headphoneRange.location != NSNotFound) return YES;

    }

    return NO;
}
like image 100
jptsetung Avatar answered Oct 02 '22 09:10

jptsetung


Here's a solution based on rob mayoff's comment:

- (BOOL)isHeadsetPluggedIn
{
    AVAudioSessionRouteDescription *route = [[AVAudioSession sharedInstance] currentRoute];

    BOOL headphonesLocated = NO;
    for( AVAudioSessionPortDescription *portDescription in route.outputs )
    {
        headphonesLocated |= ( [portDescription.portType isEqualToString:AVAudioSessionPortHeadphones] );
    }
    return headphonesLocated;
}

Simply link to the AVFoundation framework.

like image 30
ekscrypto Avatar answered Oct 02 '22 07:10

ekscrypto