Search code examples
iphoneipadios7avplayercontrol-center

Reacting to ControlCenter events when using AVPlayer for HLS audio playback


I am looking for a way to handle the play/pause events from the iOS ControlCenter when playing audio (HLS) using AVPlayer.

I have it all working, but it is based on "named" notifications which are not exposed in the header files.

Is there an "official" way to do this?

Currently the following code works:

- (void) removeControlCenterNotifications
{
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
}

- (void) addControlCenterNotifications
{
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

    __weak MyClass     *pWeakSelf   = self;
    __weak MoviePlayer *pWeakPlayer = player_;

    [[NSNotificationCenter defaultCenter] addObserverForName:@"UIApplicationSimpleRemoteActionNotification"
                                                      object:nil
                                                       queue:NULL
                                                  usingBlock:^(NSNotification *notification)
                                                  {
                                                      if(pWeakSelf == nil) return;

                                                      NSNumber *type = notification.userInfo[@"UIApplicationSimpleRemoteActionType"];

                                                      switch ([type intValue]) {
                                                          case 6: [pWeakPlayer play]; break;
                                                          case 7: [pWeakPlayer pause]; break;
                                                      }
                                                  }];
}

Solution

  • Solution

    The solution to this was to watch the UIEvents entering the app and create my own notifications from here.

    The relevant event type is:

    UIEventTypeRemoteControl
    

    The relevant event subtypes are:

    UIEventSubtypeRemoteControlPlay                 = 100,
    UIEventSubtypeRemoteControlPause                = 101,
    UIEventSubtypeRemoteControlStop                 = 102,
    UIEventSubtypeRemoteControlTogglePlayPause      = 103,
    UIEventSubtypeRemoteControlNextTrack            = 104,
    UIEventSubtypeRemoteControlPreviousTrack        = 105,
    UIEventSubtypeRemoteControlBeginSeekingBackward = 106,
    UIEventSubtypeRemoteControlEndSeekingBackward   = 107,
    UIEventSubtypeRemoteControlBeginSeekingForward  = 108,
    UIEventSubtypeRemoteControlEndSeekingForward    = 109,