avplayer no se detiene cuando se hace clic en el button de pausa si la pantalla está bloqueada

Si la aplicación está reproduciendo, la pantalla del audio y del teléfono está bloqueada y la pantalla de control se muestra a continuación. No puedo tomar ninguna acción en avplayer

introduzca la descripción de la imagen aquí

En mi appdelegate implementé:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { MPRemoteCommandCenter *rcc = [MPRemoteCommandCenter shanetworkingCommandCenter]; [[rcc skipForwardCommand] setEnabled:NO]; [[rcc skipBackwardCommand] setEnabled:NO]; [[rcc nextTrackCommand] setEnabled:NO]; [[rcc previousTrackCommand] setEnabled:NO]; [[rcc skipForwardCommand] setEnabled:NO]; [[rcc skipBackwardCommand] setEnabled:NO]; rcc.playCommand.enabled = YES; rcc.pauseCommand.enabled = YES; [[MPRemoteCommandCenter shanetworkingCommandCenter].playCommand addTarget:self action:@selector(play)]; [[MPRemoteCommandCenter shanetworkingCommandCenter].pauseCommand addTarget:self action:@selector(pause)]; } - (void) play { [[MyVideoController instance] play]; } - (void) pause { [[MyVideoController instance] pause]; } 

class MyVideoController consta de:

 - (void) pause { [self.avPlayer pause]; } - (void) play { [self.avPlayer play]; } 

Aunque estos methods se activan (se agregan puntos de corte para verificar), no se toma ninguna acción en avplayer. Pase lo que pase, avplayer no se detiene.

¿Hay alguna forma de pausar el avplayer?

EDIT 1: Agregar el código completo

En mi AppDelegate:

 - (void) remoteControlReceivedWithEvent: (UIEvent *) event { [[ZVideoPlayerController instance] eventReceived:event]; if (event.type == UIEventTypeRemoteControl) { switch (event.subtype) { case UIEventSubtypeRemoteControlTogglePlayPause: { break; } case UIEventSubtypeRemoteControlPlay: { [[ZVideoPlayerController instance] play]; break; } case UIEventSubtypeRemoteControlPause: { [[ZVideoPlayerController instance] pause]; break; } default: break; } } 

}

 - (void)applicationDidEnterBackground:(UIApplication *)application { [[UIApplication shanetworkingApplication] beginReceivingRemoteControlEvents]; [self becomeFirstResponder]; } - (void)applicationDidBecomeActive:(UIApplication *)application { [[UIApplication shanetworkingApplication] endReceivingRemoteControlEvents]; } 

ESTOY RECIBIENDO EVENTOS, PERO EL AUDIO NO SE PAUSA AL LLAMAR MÉTODO DE PAUSA EN AVPLAYER.

EDIT 2: statement de instancia en la class PlayerController

 + (instancetype)instance { static id instance = nil; if (instance == nil) { static dispatch_once_t onceToken = 0; dispatch_once(&onceToken, ^(void) { NSAssert(instance == nil, @"Singleton instance is already allocated."); instance = [[super allocWithZone:NULL] init]; }); } return instance; } 

inicializando AVPlayer

  AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil]; AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:avAsset]; AVAudioSession *session = [AVAudioSession shanetworkingInstance]; [session setCategory:AVAudioSessionCategoryPlayback error:nil]; NSError *activationError = nil; BOOL success = [[AVAudioSession shanetworkingInstance] setActive: YES error: &activationError]; NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init]; MPMediaItemArtwork *albumArt = [[MPMediaItemArtwork alloc] initWithImage: [UIImage imageNamed:@"Audio_Thumbnail_Play"]]; [songInfo setObject:title forKey:MPMediaItemPropertyTitle]; [songInfo setObject:@"100" forKey:MPMediaItemPropertyPlaybackDuration]; [songInfo setObject:albumArt forKey:MPMediaItemPropertyArtwork]; [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo]; self.avPlayer = [AVPlayer playerWithPlayerItem:playerItem]; self.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer]; 

Encontré una solución al problema. Como obtuve un valor nulo de avPlayer, utilicé mi class PageViewController para get la instancia de PlayerController. Luego utilicé la instancia de este playerController para reproducir y pausar mi avplayer porque esta instancia contiene la reference a avPlayer.

 - (PlayerController *)getVideoController { NSArray *controllers = [UtiliyClass getNavigationController].viewControllers; PageViewController *pageController = nil; for (UIViewController *cont in controllers) { if ([cont isKindOfClass:[PageViewController class]]) { pageController = (PageViewController *)cont; break; } } if (pageController == nil) { return nil; } NSArray *objectsController =pageController.pageController.viewControllers; PlayerController *videoPlayerController = nil; for (UIViewController *item in objectsController) { if ([item isKindOfClass:[PlayerController class]]) { videoPlayerController = (PlayerController *)item; break; } } return videoPlayerController; } - (void) pause { PlayerController *controller = [self getVideoController]; [controller.avPlayer pause]; } - (void) play { PlayerController *controller = [self getVideoController]; [controller.avPlayer play]; } 

Necesita registrarse para la notificación remota para actualizar el estado del reproductor cuando la aplicación está bloqueada. Para eso, siga los siguientes pasos:

Agregue esto en su AppDelegate, idealmente en applicationDidEnterBackground:

 [[UIApplication shanetworkingApplication] beginReceivingRemoteControlEvents]; [self becomeFirstResponder]; 

Y esto en applicationDidBecomeActive:

 [[UIApplication shanetworkingApplication] endReceivingRemoteControlEvents]; 

Reciba notifcaciones remotas agregando esto en AppDelagate. Esto escuchará todas las acciones cuando el teléfono esté bloqueado.

 - (void)remoteControlReceivedWithEvent:(UIEvent *)event { if (event.type == UIEventTypeRemoteControl){ // Call method of your player where you want to make change (Pause , Paly), // I am calling a shanetworking view for example, Its up to your logic how you want to deal it [[AudioPlayerView shanetworkingPlayerView] remoteControlReceivedWithEvent:event]; } } 

Y en eso, obtenga su evento deseado y actualícelo según corresponda.

  - (void)remoteControlReceivedWithEvent:(UIEvent *)event { if (event.type == UIEventTypeRemoteControl){ switch (event.subtype){ case UIEventSubtypeRemoteControlPlay: [[MyVideoController instance] play]; break; case UIEventSubtypeRemoteControlPause: [[MyVideoController instance] pause]; break; case UIEventSubtypeRemoteControlTogglePlayPause: // Check if state is playing , call pause else call play break; } default: break; } } } 

En iOS 7.1 y posterior, use el object compartido MPRemoteCommandCenter para registrarse para events de control remoto. No necesita llamar a este método cuando usa el object central de command compartido. Este método inicia la entrega de events de control remoto utilizando la cadena de respuesta. Los events de control remoto se originan como commands emitidos por auriculares y accesorios externos que están destinados a controlar multimedia presentados por una aplicación. Para detener la recepción de events de control remoto, debe llamar a endReceivingRemoteControlEvents ().

Agregue este código siguiente para in didfinishlunching para la temporada de audio de init y obtenga un evento de control remoto:

  // Initialize the AVAudioSession here. if (![[AVAudioSession shanetworkingInstance] setCategory:AVAudioSessionCategoryPlayback error:&myErr]) { // Handle the error here. NSLog(@"Audio Session error %@, %@", myErr, [myErr userInfo]); } else{ // Since there were no errors initializing the session, we'll allow begin receiving remote control events [[UIApplication shanetworkingApplication] beginReceivingRemoteControlEvents]; } 

Para recibir el commadn use este código:

 - (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent { if (receivedEvent.type == UIEventTypeRemoteControl) { switch (receivedEvent.subtype) { case UIEventSubtypeRemoteControlPreviousTrack: break; case UIEventSubtypeRemoteControlNextTrack: break; case UIEventSubtypeRemoteControlPlay: [[MyVideoController instance] play]; break; case UIEventSubtypeRemoteControlPause: [[MyVideoController instance] pause]; break; default: break; } } } 
    Intereting Posts