Sunday, November 2, 2014

iOS How to Check if Head set is connected

There are couple of options suggested in the blogs to find whether headset is plugged into an iOS device. 

Below are the two ways we can check the audio route changes

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

- (BOOL)isHeadsetPluggedIn3 {
    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 = (__bridge NSString*)route;
        
        NSRange headphoneRange = [routeStr rangeOfString : @"Head"];
        
        if (headphoneRange.location != NSNotFound) return YES;
        
    }
    
    return NO;
}

Both the above approaches work, but  isHeadsetPluggedIn3 uses the AudioSessionGetProperty which is deprecated in iOS 5.0 onwards and gives warning. 

The method isHeadsetPluggedIn2 looks to be good. 

References:
http://stackoverflow.com/questions/3728781/detect-if-headphones-not-microphone-are-plugged-in-to-an-ios-device

No comments:

Post a Comment