2010-12-06 19 views
23

estoy tratando de poner dos MPMoviePlayerController en un UIView como estocasos MPMoviePlayerController múltiples

for (int i = 0; i < 2; i++) 
{ 
    UIView* v = [[UIView alloc] initWithFrame: CGRectMake(0.0f, 300.0f * i, self.view.width, 300.0f)]; 
    [self.view addSubview: v]; 

    NSURL* url = [NSURL URLWithString: [urls objectAtIndex: i]]; 
    MPMoviePlayerController* movieController = [[MPMoviePlayerController alloc] initWithContentURL: url]; 
    movieController.movieSourceType = MPMovieSourceTypeFile; 
    movieController.shouldAutoplay = NO; 
    movieController.view.frame = v.bounds; 
    [self.view addSubview: movieController.view]; 
} 

Pero sólo se muestra una visión a la vez. Sé que la documentación de Apple dice

Nota: Aunque puede crear múltiples objetos MPMoviePlayerController y presentar sus vistas en su interfaz, solo un reproductor de película a la vez puede reproducir su película.

pero ¿no debería la vista mostrar los dos jugadores a la vez? Además, solo una instancia envía notificaciones MPMoviePlayerLoadStateDidChangeNotification ...

+0

¿Encontró una respuesta a esto? – Pompair

+0

No. Fue forzado a usar un UIWebView con videos incrustados. –

Respuesta

0

¿Necesita reproducir ambos videos simultáneamente?

supongo que tengo dos opciones:

  1. añadir dos botones de imagen miniatura de vídeo en la misma pantalla. Según la selección, se reproduce el video seleccionado y otro se detiene. Por lo tanto, en un momento a la vista, solo se reproducirá un solo video.

  2. Crea un controlador de vista separado y agrega tu video a eso. Ahora agrega ese viewcontroller.view en tu vista principal donde quieras.

Avísame si alguno de estos te sirve.

1

No podrá hacer esto. Internamente, MPMoviePlayerController parece usar la misma vista para intercambiar instancias dependiendo de la instancia que se esté reproduciendo. Su única opción es desarrollar su propio reproductor de video utilizando AVFoundation para obtener varias instancias o usar HTML y UIWebViews. Ver: http://developer.apple.com/library/ios/#documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/00_Introduction.html#//apple_ref/doc/uid/TP40010188

+0

Simplemente está roto: si abre dos MPMoviePlayerViewController en la misma pantalla, ¡simplemente se oscurecen y nada funciona! (Dec 2013.) – Fattie

+2

En realidad, el último que se agregó reproduce el video, pero los demás solo muestran los colores de fondo. – erkanyildiz

27

Usted puede reproducir varios vídeos en la pantalla utilizando el marco AVFoundation: AV Foundation Programming Guide

La desventaja es, que no es tan fácil de usar como el MPMoviePlayerController, y shoul crear una subclase UIView cuales contiene las clases AVFoundation. De esta forma puede crear los controles necesarios para ello, controlar la reproducción de video, animar la vista (por ejemplo, animar la transición a pantalla completa).

Aquí es como lo he usado:

// Create an AVURLAsset with an NSURL containing the path to the video 
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil]; 

// Create an AVPlayerItem using the asset 
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:asset]; 

// Create the AVPlayer using the playeritem 
AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem]; 

// Create an AVPlayerLayer using the player 
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player]; 

// Add it to your view's sublayers 
[self.layer addSublayer:playerLayer]; 

// You can play/pause using the AVPlayer object 
[player play]; 
[player pause]; 

// You can seek to a specified time 
[player seekToTime:kCMTimeZero]; 

// It is also useful to use the AVPlayerItem's notifications and Key-Value 
// Observing on the AVPlayer's status and the AVPlayerLayer's readForDisplay property 
// (to know when the video is ready to be played, if for example you want to cover the 
// black rectangle with an image until the video is ready to be played) 
[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(playerItemDidReachEnd:) 
              name:AVPlayerItemDidPlayToEndTimeNotification 
              object:[player currentItem]]; 

    [player addObserver:self forKeyPath:@"currentItem.status" 
        options:0 
        context:nil]; 

    [playerLayer addObserver:self forKeyPath:@"readyForDisplay" 
        options:0 
        context:nil]; 

puede cambiar el tamaño AVPlayerLayer como desee, incluso mientras se reproduce el video.

Si desea utilizar animaciones mientras cambia el tamaño o reposiciona su AVPlayerLayer, debe modificar sus animaciones predeterminadas, de lo contrario verá que el video de la capa del reproductor no cambia de tamaño en sincronización con su rect. (Gracias a @djromero por su answer regarding the AVPlayerLayer animation)

Aquí hay un pequeño ejemplo de cómo alterar su animación predeterminada. La configuración para este ejemplo es que AVPlayerLayer está en una subclase UIView que actúa como contenedor:

// UIView animation to animate the view 
[UIView animateWithDuration:0.5 animations:^(){ 
    // CATransaction to alter the AVPlayerLayer's animation 
    [CATransaction begin]; 
    // Set the CATransaction's duration to the value used for the UIView animation 
    [CATransaction setValue:[NSNumber numberWithFloat:0.5] 
        forKey:kCATransactionAnimationDuration]; 
    // Set the CATransaction's timing function to linear (which corresponds to the 
    // default animation curve for the UIView: UIViewAnimationCurveLinear) 
    [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction 
          functionWithName:kCAMediaTimingFunctionLinear]]; 

     self.frame = CGRectMake(50.0, 50.0, 200.0, 100.0); 
     playerLayer.frame = CGRectMake(0.0, 0.0, 200.0, 100.0); 

    [CATransaction commit]; 

}]; 
+1

Increíble respuesta .... gracias – Fattie

+0

@Alpar - Esto funciona como encanto, pero una pregunta. ¿Por qué al agregar el observador AVPlayerItemDidPlayToEndTimeNotification el objeto se da como [player currentItem]? ¿Qué pasa si solo digo jugador? Si especifico jugador, la notificación se envía para todas las instancias de video. –

+0

Gracias, trabajado como un encanto –

Cuestiones relacionadas