2011-10-25 124 views
0

我試圖檢測連接到iPhone的耳機上的用戶輸入(單擊)。到目前爲止,我只找到了如何使用AVAudioSession檢測中斷。 AVAudioSession是正確的還是有另一種方式?怎麼樣?使用耳機檢測用戶輸入

回答

1

你想這樣的:

beginReceivingRemoteControlEvents

你在你的VC類的一個實現一些這樣的:

// If using a nonmixable audio session category, as this app does, you must activate reception of 
// remote-control events to allow reactivation of the audio session when running in the background. 
// Also, to receive remote-control events, the app must be eligible to become the first responder. 
- (void) viewDidAppear: (BOOL) animated { 

    [super viewDidAppear: animated]; 
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; 
    [self becomeFirstResponder]; 
} 

- (BOOL) canBecomeFirstResponder { 

    return YES; 
} 


    // Respond to remote control events 

- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent { 

    if (receivedEvent.type == UIEventTypeRemoteControl) { 

     switch (receivedEvent.subtype) { 

      case UIEventSubtypeRemoteControlTogglePlayPause: 
       [self playOrStop: nil]; 
       break; 

      default: 
       break; 
     } 
    } 
} 

見示例代碼here

+0

出於某種原因,這是行不通的。我讀過,也許你必須初始化一個AVAudioSession?真的不知道,我試圖做這項工作,但失敗了。 – jglievano

+0

下載示例代碼,看看它是否適合你。然後仔細檢查你的VC是否有我發佈的這些方法。如果它不在響應者鏈中,它將不會收到通知。 – logancautrell

+0

實際上示例代碼也不起作用。我的意思是,你必須按下播放按鈕才能使耳機按鈕首先工作。 – jglievano

1

它當按下耳機播放/暫停按鈕現在更容易,因爲iOS的7執行塊的:

MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter]; 

    [commandCenter.togglePlayPauseCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) { 
     NSLog(@"toggle button pressed"); 
     return MPRemoteCommandHandlerStatusSuccess; 
    }]; 

或者,如果你喜歡使用的方法,而不是一個塊:

[commandCenter.togglePlayPauseCommand addTarget:self action:@selector(toggleButtonAction)]; 

要停止:

[commandCenter.togglePlayPauseCommand removeTarget:self]; 

或:

[commandCenter.togglePlayPauseCommand removeTarget:self action:@selector(toggleButtonAction)]; 

你需要添加此到包括文件的區域:

@import MediaPlayer;