在ios6以前,我们有如下的方法:
#import<AVFoundation/AVFoundation.h>
[[AVAudioSession sharedInstance] setDelegate:self];
AudioSessionAddPropertyListener(kAudioSessionProperty_AudioRouteChange,audioRouteChangeListenerCallback, self);
然后实现该回调://音频监控回调函数
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
}
请注意[[AVAudioSession sharedInstance] setDelegate:self]一定不要遗漏,否则该回调应该无法触发。[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(outputDeviceChanged:)name:AVAudioSessionRouteChangeNotificationobject:[AVAudioSessionsharedInstance]];
- (void)outputDeviceChanged:(NSNotification *)aNotification
{
// do your jobs here
}
请注意,addobserver的参数填写:其中的object必须是[AVAudioSession sharedInstance],而不是我们通常很多情况下填写的nil,此处若为nil,通知也不会触发。