Ios listening for output device changes (Listening for headset plugging, Bluetooth device disconnection, etc.)
Before ios6, we had the following methods:
# Import
[[AVAudioSession sharedInstance] setDelegate: self];
AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, audioRouteChangeListenerCallback, self );
Then implement the callback:
// Audio monitoring callback function
Static void audioRouteChangeListenerCallback (void * inUserData,
AudioSessionPropertyID inPropertyID,
UInt32 inPropertyValueSize,
Constvoid * inPropertyValue
)
{
If (inPropertyID! = KAudioSessionProperty_AudioRouteChange)
{
Return;
}
// Determines the reason for the route change, to ensure that it is not
// Because of a category change.
CFDictionaryRef routeChangeDictionary = inPropertyValue;
CFNumberRef routeChangeReasonRef = CFDictionaryGetValue (routeChangeDictionary, CFSTR (kAudioSession_AudioRouteChangeKey_Reason ));
SInt32 routeChangeReason;
CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, & routeChangeReason );
// Do your handling here
}
Note that [[AVAudioSession sharedInstance] setDelegate: self] must not be omitted; otherwise, this callback cannot be triggered.
---------------------- Split line ------------------------ the above method is the implementation method before ios6. We can see that this api is a relatively low-level implementation, and its callback is the implementation method of c, rather than the oc implementation that we normally use. Therefore, after ios6 and later, the above api is deprecated (of course, if you still use it, you can still implement the function). We have better and more advanced implementations to solve the problem:
[[Nsnotificationcenterdefacenter] addObserver: selfselector: @ selector (outputDeviceChanged :) name: avaudiosessionroutechangenotificationicationobject: [AVAudioSessionsharedInstance];
-(Void) outputDeviceChanged :( NSNotification *) aNotification
{
// Do your jobs here
}
Note that the addobserver parameter must be set to [AVAudioSession sharedInstance], rather than the nil that we usually fill in many cases. If it is nil, the notification will not be triggered.