你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS - 檢測耳機孔是否存在耳機:

iOS - 檢測耳機孔是否存在耳機:

編輯:IOS開發綜合



- (id)init
{
    self = [super init];
    if (self)
    {
        /*
         OSStatus AudioSessionInitialize (
         CFRunLoopRef                      inRunLoop,               //運行循環的中斷監聽器回調應該被運行。傳遞NULL,使用主運行循環。
         CFStringRef                       inRunLoopMode,           //該模式的運行循環的中斷監聽功能將運行在。傳遞NULL,就相當於通過kCFRunLoopDefaultMode
         AudioSessionInterruptionListener  inInterruptionListener,  //中斷監聽器回調函數。應用程序的音頻會話對象調用回調時,會話被中斷及(如應用程序仍在運行)中斷結束時。可以為NULL。見AudioSessionInterruptionListener
         void                              *inClientData            //想傳遞給你的中斷監聽器回調。
         );
         */
        AudioSessionInitialize(NULL, NULL, NULL, NULL);
        AudioSessionAddPropertyListener(kAudioSessionProperty_AudioRouteChange, audioRouteChangeCallback, (__bridge void *)(self));
    }
    return self;
}

- (BOOL)isHeadphone
{
    UInt32 propertySize = sizeof(CFStringRef);
    CFStringRef state 	= nil;
    AudioSessionGetProperty(kAudioSessionProperty_AudioRoute ,&propertySize,&state);
    
    //根據狀態判斷是否為耳機狀態
    if ([(__bridge NSString *)state isEqualToString:@"Headphone"] ||[(__bridge NSString *)state isEqualToString:@"HeadsetInOut"])
        return YES;
    else
        return NO;
}

void audioRouteChangeCallback(void *inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void *inData)
{
    
    SInt32 routeChangeReason;
    CFDictionaryRef routeChangeDictionary = inData;
    CFNumberRef routeChangeReasonRef	  = CFDictionaryGetValue(routeChangeDictionary, CFSTR(kAudioSession_AudioRouteChangeKey_Reason));
    
    CFNumberGetValue(routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
    
    if (routeChangeReason      == kAudioSessionRouteChangeReason_OldDeviceUnavailable) {  //拔掉
        
        
    }
    else if (routeChangeReason == kAudioSessionRouteChangeReason_NewDeviceAvailable) {    //插入
        
        [[MPMusicPlayerController applicationMusicPlayer] setVolume:1.0];
        
        
    }
    else if (routeChangeReason == kAudioSessionRouteChangeReason_NoSuitableRouteForCategory) {
        
    }
}




  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved