10

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

我设法使用以下方法检测到音量按钮的点击:

AudioSessionAddPropertyListener( kAudioSessionProperty_CurrentHardwareOutputVolume , audioVolumeChangeListenerCallback, self );

但我找不到中心按钮的 AudioSessionProperty。这样做的方法是什么?

4

3 回答 3

8

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

这是iOS 远程事件的事件处理指南。

就个人而言,我喜欢继承 MainWindow ( UIWindow) 并覆盖该sendEvent:方法,因此我可以更直接地管理它:

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

希望对您有所帮助,中央按钮事件的枚举是UIEventSubtypeRemoteControlTogglePlayPause.

于 2011-09-18T05:48:07.203 回答
2

以上都试过了,但遗憾的是现在似乎都没有。然后我看了一眼,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 的 didFinishLaunching 时,报告的事件是不同的。无论哪种方式,都会检测到事件。

于 2019-10-05T14:59:13.320 回答
1

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]));
  }
}

代码MyUIApplication.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

代码AppDelegate.m

代替- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

称呼[application beginReceivingRemoteControlEvents];

于 2017-10-18T04:58:42.760 回答