检测耳机按钮点击iPhone SDK

检测耳机按钮点击iPhone SDK,iphone,sdk,detect,headset,Iphone,Sdk,Detect,Headset,是否有办法检测耳机的播放/暂停按钮点击 我设法通过以下方式检测音量按钮的点击: AudioSessionAddPropertyListener( kAudioSessionProperty_CurrentHardwareOutputVolume , audioVolumeChangeListenerCallback, self ); 但是我找不到中心按钮的AudioSessionProperty。怎么做呢?从应用程序外部执行的所有操作都被视为“远程事件”。如果您双击Home(主页)按钮并在此处

是否有办法检测耳机的播放/暂停按钮点击

我设法通过以下方式检测音量按钮的点击:

AudioSessionAddPropertyListener( kAudioSessionProperty_CurrentHardwareOutputVolume , audioVolumeChangeListenerCallback, self );

但是我找不到中心按钮的AudioSessionProperty。怎么做呢?

从应用程序外部执行的所有操作都被视为“远程事件”。如果您双击Home(主页)按钮并在此处按Play(播放)/Pause(暂停)按钮,则相当于按耳机上的Play(播放)/Pause(暂停)按钮(下一次按两次相同,上一次按三次相同)

这是火车上的指南

就我个人而言,我喜欢对主窗口(
UIWindow
)进行子类化,并重写
sendEvent:
方法,以便更直接地管理它:

- (void)sendEvent:(UIEvent *)event
{
    if (event.type == UIEventTypeRemoteControl)
    {
        // Do stuff here
    }
    else
    {
        // Not my problem.
        [super sendEvent:event];
    }
}

希望有帮助,中央按钮事件的枚举是
uieventSubmitRemoteControlTogglePlayPause
Can的答案很好,但我认为它已经过时了

现在您需要对UIApplication进行子类化

main.m的代码

#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "MyUIApplication.h"

int main(int argc, char * argv[]) {
  @autoreleasepool {
    return UIApplicationMain(
      argc,
      argv,
      NSStringFromClass([MyUIApplication class]),
      NSStringFromClass([AppDelegate class]));
  }
}
AppDelegate.m的代码:

@implementation MyUIApplication
- (void)sendEvent:(UIEvent *)event {
  if (event.type == UIEventTypeRemoteControl) {
    // Check event.subtype to see if it's a single click, double click, etc.
  } else {
    // Not my problem.
    [super sendEvent:event];
  }
}
@end
-(BOOL)应用程序的内部:(UIApplication*)应用程序使用选项完成启动:(NSDictionary*)启动选项{


调用
[application beginReceivingRemoteControlEvents];

尝试了以上所有方法,但遗憾的是,现在似乎没有一种方法有效。 然后我看了一眼beginReceivingRemoteControlEvents,发现了这个

在iOS 7.1及更高版本中,使用共享MPRemoteCommandCenter对象注册远程控制事件。使用共享命令中心对象时,不需要调用此方法

然后签出
MPRemoteCommandCenter
,最后进入
MPRemoteCommand
文档页面

好消息是有这样一个例子:

let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.playCommand.addTarget(handler: { (event) in    

    // Begin playing the current track    
    self.myMusicPlayer.play()
    return MPRemoteCommandHandlerStatus.success
})
现在,如果我们想阅读中间按钮,我们可以:

MPRemoteCommandCenter.shared().togglePlayPauseCommand.addTarget { (event: MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus in

 // middle button (toggle/pause) is clicked
 print("event:", event.command)

 return .success
}
这是可行的,我成功地检测到了耳机的中间按钮

注: 我注意到有不同的行为,这取决于我们把这些代码放在上面的什么地方。
也就是说,当我将其放入View Controller时,报告的事件是相同的,当我将其放入AppDelegate的DidFinish启动时,报告的事件是不同的。无论哪种方式,都会检测到该事件。

谢谢。我使用以下方法找到了另一个解决方案:“remoteControlReceivedWithEvent:”。解决方案在此讨论:@我可以尝试您的解决方案吗?当我按下耳机上的按钮时,sendEvent UIEventTypeRemoteControl事件类型不会被调用。您是否进行了其他设置以使其工作?子类正在工作,因为我捕获了一些其他事件。此外,您必须播放一些内容才能重新启动根据文档接收这些事件->