1

I'm trying to detect when headphones are plugged into the iPhone. I do this buy the following approach.

//Init the AVAudioSession
-(void)viewDidLoad
{
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&error];    
    NSError *activationError = nil;

    [[AVAudioSession sharedInstance] setActive: YES error: &activationError];
}

//Get the current audio session route
-(void)viewWillAppear
{
    AVAudioSessionRouteDescription  *route = [[AVAudioSession sharedInstance] currentRoute];
}

This works fine and the route.inputs and route.outputs will contain the headphones and the microphone for a wired iPhone headset and will show the built in receiver and built in microphone when the headphones are unplugged. The problem I'm running into is when I press the home button on my app and it moves to the background. When I bring the app back into the foreground the route.inputs is always empty. My question is: Do I need to set the [[AVAudioSession sharedInstance] setActive:NO error: &activiationError] in my appDelegate when applicaionWillResign active is called? Because when route.inputs comes back empty, the headphones are still plugged in and should be detected. Any help would be appreciated. Thank you.

P.J.Radadiya
  • 1,493
  • 1
  • 12
  • 21
zic10
  • 2,310
  • 5
  • 30
  • 55

1 Answers1

1

I think a better approach is this :

- (BOOL)isHeadsetPluggedIn 
{
    AVAudioSessionRouteDescription* route = [[AVAudioSession sharedInstance] currentRoute];
    for (AVAudioSessionPortDescription* desc in [route outputs]) 
    {
        if ([[desc portType] isEqualToString:AVAudioSessionPortHeadphones])
            return YES;
    }
    return NO;
}

I just tested this and this works even when coming back to foreground from background, and also on viewDiDLoad

Link to Original Answer

Community
  • 1
  • 1
benzino
  • 46
  • 4