iphoneipodaudio-player

How to programmatically detect earpiece in iphone?


I'm currently working on a project that involves playing music from the iphone music library within the app inside. I'm using MPMediaPickerController to allow the user to select their music and play it using the iPod music player within the iPhone.

However, i ran into problem when the user insert his earpiece and removes it. The music will suddenly stop playing for no reason. After some testing, i found out that the iPod player will pause playing when the user unplug his earpiece from the device. So is there any way to programatically detect if the earpiece has been unplug so that i can resume playing the music? Or is there any way to prevent iPod player from pausing when the user unplug his earpiece?


Solution

  • You should register for AudioRoute changed notification and implement how you want to handle the rout changes

        // Registers the audio route change listener callback function
        AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange,
                                         audioRouteChangeListenerCallback,
                                         self);
    

    and within the callback, you can get the reason for route change

      CFDictionaryRef   routeChangeDictionary = inPropertyValue;
    
      CFNumberRef routeChangeReasonRef =
      CFDictionaryGetValue (routeChangeDictionary,
                CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
    
      SInt32 routeChangeReason;
    
          CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
    
      if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable) 
      {
           // Headset is unplugged..
    
      }
      if (routeChangeReason == kAudioSessionRouteChangeReason_NewDeviceAvailable)
      {
           // Headset is plugged in..                   
      }