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

San*_*ram 8 objective-c uievent iphone-5 ios6.1

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

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

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

slo*_*ans 13

还有另一种通过耳机实现播放器控制的方法.使用MPRemoteCommandCentertooglePlayPauseCommand. Apple文档

[[MPRemoteCommandCenter sharedCommandCenter].togglePlayPauseCommand addTarget:self action:@selector(onTooglePlayPause)];
Run Code Online (Sandbox Code Playgroud)


Ban*_*tal 12

您必须检查此标准:

  1. 编辑info.plist以规定您在后台和前台执行音频(UIBackgroundModes).
  2. 实现此功能:

    - (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;
        }
      }
    }
    
    Run Code Online (Sandbox Code Playgroud)

...显然,将"// insert code"替换为应用程序中相关的任何功能.

3>最后,为了调用上面的函数,将其插入到viewDidAppear事件中:

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    if ([self canBecomeFirstResponder]) {
        [self becomeFirstResponder];
    }
Run Code Online (Sandbox Code Playgroud)

另请看这个链接:http: //www.sagorin.org/2011/11/29/ios-playing-audio-in-background-audio/