Objective c 我们如何在ios中处理前台的耳机播放/暂停按钮事件

Objective c 我们如何在ios中处理前台的耳机播放/暂停按钮事件,objective-c,iphone-5,ios6.1,uievent,Objective C,Iphone 5,Ios6.1,Uievent,我要求在前台处理耳机播放/暂停按钮事件。我如何能够使用下面的代码在后台处理相同的场景 if ([[UIApplication sharedApplication] respondsToSelector:@selector(beginReceivingRemoteControlEvents)]){ [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; [[UIApplication shared

我要求在前台处理耳机播放/暂停按钮事件。我如何能够使用下面的代码在后台处理相同的场景

if ([[UIApplication sharedApplication] respondsToSelector:@selector(beginReceivingRemoteControlEvents)]){
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
    [self becomeFirstResponder];
    NSLog(@"Responds!");
}

如果可能,请提供解释或示例代码。我做了很多研究,但没有任何帮助。

您必须检查以下标准:

  • 编辑您的info.plist以规定您在后台和前台都使用音频(UIBackgroundModes)
  • 实现此功能:

    - (void)remoteControlReceivedWithEvent:(UIEvent *)theEvent 
    {
      if (theEvent.type == UIEventTypeRemoteControl)
      {
        switch(theEvent.subtype) {
        case UIEventSubtypeRemoteControlTogglePlayPause:
                //Insert code
                break;
            case UIEventSubtypeRemoteControlPlay:
                //Insert code
                break;
            case UIEventSubtypeRemoteControlPause:
                // Insert code
                break;
            case UIEventSubtypeRemoteControlStop:
                //Insert code.
                break;
            default:
                return;
        }
      }
    }
    
  • …显然,用应用程序中相关的功能替换“//插入代码”

    3> 最后,为了调用上述函数,请在ViewDidDisplay事件中插入以下内容:

    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
        if ([self canBecomeFirstResponder]) {
            [self becomeFirstResponder];
        }
    
    另请参阅此链接:

    还有另一种通过耳机实现播放器控制的方法。 使用
    MPRemoteCommandCenter
    tooglePlayPauseCommand。


    斯洛博丹解决方案的swift 2版本:

    MPRemoteCommandCenter.sharedCommandCenter().togglePlayPauseCommand.addTarget(self, action: #selector(togglePlayStop(_:)));
    

    谢谢你的回复,但是我可以在后台处理事件,我也在plist中添加了UIBackgroundModes,但是我不知道前台事件的处理。我尝试过触发提到的方法“-(void)remoteControlReceivedWithEvent:(UIEvent*)theEvent”,但没有成功。你能告诉我如何在plist中添加前景键吗?2分钟后,如果按耳机按钮,音乐应用程序启动并播放上一个声音。
    MPRemoteCommandCenter.sharedCommandCenter().togglePlayPauseCommand.addTarget(self, action: #selector(togglePlayStop(_:)));