【问题标题】:How can we handle headphone play/pause button events in foreground in ios我们如何在ios的前台处理耳机播放/暂停按钮事件
【发布时间】:2013-03-03 16:55:56
【问题描述】:

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

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

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

【问题讨论】:

    标签: objective-c iphone-5 ios6.1 uievent


    【解决方案1】:

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

    [[MPRemoteCommandCenter sharedCommandCenter].togglePlayPauseCommand addTarget:self action:@selector(onTooglePlayPause)];
    

    【讨论】:

      【解决方案2】:

      您必须检查以下条件:

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

      ...显然,将“//插入代码”替换为您的应用中相关的任何功能。

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

      [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
          if ([self canBecomeFirstResponder]) {
              [self becomeFirstResponder];
          }
      

      另请参阅此链接: http://www.sagorin.org/2011/11/29/ios-playing-audio-in-background-audio/

      【讨论】:

      • 感谢您的回复,但是我能够在后台处理事件,我也在 plist 中添加了 UIBackgroundModes,但我不知道前台事件处理。我试过触发提到的方法'- (void)remoteControlReceivedWithEvent:(UIEvent *)theEvent',但没有运气。你能解释一下我们如何在 plist 中添加前台键。
      • 2分钟后,如果按下耳机按钮,音乐应用会启动并播放上一个声音。
      【解决方案3】:

      slobodans 解决方案的 swift 2 版本:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-10
        • 2012-02-03
        • 1970-01-01
        • 2011-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多