How can we handle headphone play/pause button events in foreground in ios

落花浮王杯 提交于 2019-12-03 04:04:09

There is another way to implement player control from headphones. use MPRemoteCommandCenter tooglePlayPauseCommand. Apple documentation

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

You must check this criteria:

  1. Edit your info.plist to stipulate that you do audio (UIBackgroundModes) in the background as well as foreground.
  2. Implement this function:

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

...obviously, replace the "//insert code" with whatever functionality is relevent in your app.

3>Finally, in order for that above function to be called, insert this in your viewDidAppear event:

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

also please see this link: http://www.sagorin.org/2011/11/29/ios-playing-audio-in-background-audio/

The swift 2 version for slobodans solution:

MPRemoteCommandCenter.sharedCommandCenter().togglePlayPauseCommand.addTarget(self, action: #selector(togglePlayStop(_:)));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!