ios監聽輸出裝置變化(監聽耳機插拔,藍牙裝置串連斷開等)的實現
在ios6以前,我們有如下的方法:
#import
[[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]一定不要遺漏,否則該回調應該無法觸發。
------------------------分割線------------------------上面的方法是ios6以前的實現方式,我們可以看出這個api是比較低級的實現,其回調還是c的實現方式,而不是我們平常習慣的oc實現。因此在ios6及以後,上面的api被deprecated了(當然,你要是還這麼用,也還是能夠實現功能),我們有更好更進階的實現來解決問題:
[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(outputDeviceChanged:)name:AVAudioSessionRouteChangeNotificationobject:[AVAudioSessionsharedInstance]];
- (void)outputDeviceChanged:(NSNotification *)aNotification
{
// do your jobs here
}
請注意,addobserver的參數填寫:其中的object必須是[AVAudioSession sharedInstance],而不是我們通常很多情況下填寫的nil,此處若為nil,通知也不會觸發。