Before IOS6, we have the following methods:
#import<AVFoundation/AVFoundation.h>
[[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,
Const void *inpropertyvalue
)
{
if (Inpropertyid! =kaudiosessionproperty_audioroutechange)
{
return;
}
//Determines the reason for the ensure
//Because of a category change.
cfdictionaryref routechangedictionary = inpropertyvalue;
cfnumberref routechangereasonref = cfdictionarygetvalue (routechangedictionary, cfstr ( C4>kaudiosession_audioroutechangekey_reason));
SInt32 Routechangereason;
Cfnumbergetvalue (Routechangereasonref,kcfnumbersint32type, &routechangereason);
Do your handling here
}
Please note[[avaudiosessionsharedinstance] setdelegate: Self] must not be omitted, otherwise the callback should not be triggered.
------------------------Split Line------------------------the above method is IOS6 the previous implementation, we can see that this API is a relatively low-level implementation, its callback or C implementation, rather than our usual practice of OC implementation. so in IOS6 and beyond, the API is deprecated (of course, if you still use it, you can still implement the function), we have a better and more advanced implementation to solve the problem:
[[nsnotificationcenterdefaultcenter] addobserver: Self selector:@selector(outputdevicechanged:) Name:avaudiosessionroutechangenotificationObject: [ Avaudiosessionsharedinstance]];
-(void) outputdevicechanged: (nsnotification *) anotification
{
Do your jobs here
}
Please note that the parameters of the addobserver are filled in: the object must be[avaudiosession sharedinstance], instead of nil, which we usually fill in many cases, the notification will not be triggered if nil is here.
iOS monitor output device changes (monitor headset plug-and-unplug, Bluetooth device connection disconnect, etc.) implementation