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

后端 未结 3 651
南旧
南旧 2021-02-06 05:31

I have an requirement that to handle headphone play/pause button events in foreground. How ever I am able to handle the same scenario in background using the below code

3条回答
  •  渐次进展
    2021-02-06 06:23

    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/

提交回复
热议问题