ios监听输出设备变化(监听耳机插拔,蓝牙设备连接断开等)的实现

 在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 ]一定不要遗漏,否则该回调应该无法触发。

------------------------分割线------------------------
上面的方法是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,通知也不会触发。







你可能感兴趣的:(ios监听输出设备变化(监听耳机插拔,蓝牙设备连接断开等)的实现)