2009-11-11 73 views
4

我正在使用AVAudioPlayer類在我的應用程序中播放.mp3文件。是否可以檢查耳機是否以編程方式連接到設備?以編程方式檢查連接到設備的耳機嗎?

在第一代iPod設備中,當沒有耳機連接時,音量控制欄將隱藏(用於音樂和視頻)。

+0

http://stackoverflow.com/questions/667196/detected-iphone-ipod-touch-accessories – Les 2009-11-11 09:45:48

+0

感謝您的更正。 – Biranchi 2009-11-11 10:02:10

回答

5

您可以撥打AudioSessionGetProperty並使用kAudioSessionProperty_AudioRoute屬性獲取當前的音頻路由。 這給你一個字符串,如「耳機」或「揚聲器」。

您還可以使用AudioSessionAddPropertyListener監聽時,路線的變化(如斷開耳機。)

看到蘋果文檔here

0

有兩種方法:

1)檢查音頻路由的瞬時狀態

Detect if headphones (not microphone) are plugged in to an iOS device

這個答案爲您創造一個現成的方法檢測是否耳機插好。

2)監控路由變化事件,並設置一個標誌,每當耳機和非耳機之間的路由變化

How to programmatically detect earpiece in iphone?

(可能會想從第一個鏈接到該代碼添加到實際確定是否耳機/非耳機地位路線改變CA內被改變llback)

2

AudioSessionGetPropertyAudioSessionAddPropertyListener在iOS的7

已被棄用相反,使用:AVAudioSessionRouteChangeNotification

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleRouteChange:) name:AVAudioSessionRouteChangeNotification object:nil]; 

監聽器,

-(void)handleRouteChange:(NSNotification*)notification 
{ 
    NSInteger reason = [[[notification userInfo] objectForKey:AVAudioSessionRouteChangeReasonKey] integerValue]; 
    switch (reason) { 
     case AVAudioSessionRouteChangeReasonOldDeviceUnavailable : 
      break; 
     case AVAudioSessionRouteChangeReasonNewDeviceAvailable : 
      break; 
     case AVAudioSessionRouteChangeReasonOverride : 
      break; 
     case AVAudioSessionRouteChangeReasonCategoryChange : 
      break; 
     case AVAudioSessionRouteChangeReasonWakeFromSleep : 
      break; 
     case AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory : 
      break; 
     case AVAudioSessionRouteChangeReasonRouteConfigurationChange : 
      break; 
     case AVAudioSessionRouteChangeReasonUnknown: 
     default: 
      break; 
    } 
} 
+0

有時,AVAudioSession通知不會在主隊列中調用。這樣包裝塊內部的方法將避免相關問題(更新UI ...): 'dispatch_async(dispatch_get_main_queue()^ {// 您的方法 });' – nahung89 2015-08-11 04:42:17

+0

@ nahung89如果通知不調用在主隊列中使用主隊列的優點是什麼? – 2017-10-04 07:49:47

+0

@ Fa.Shapouri正如我在上面的評論中指出的,你應該仔細閱讀。 – nahung89 2017-10-04 09:05:26

相關問題