使用耳机检测用户输入

时间:2011-10-25 20:21:47

标签: iphone input avaudiosession headset

我正在尝试检测连接到iPhone的耳机上的用户输入(点击)。到目前为止,我只发现了如何使用AVAudioSession检测中断。 AVAudioSession是对的还是另一种方式?如何?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;
相关问题