2010-11-18 11 views
6

La película se reproduce bien pero hay un destello negro rápido justo antes de que se reproduzca. ¿Es esto un capricho resultante de establecer el estilo de control a MPMovieControlStyleNone?MPMoviePlayerController provoca un destello de negro al inicio del video

NSString *url = [[NSBundle mainBundle] pathForResource:@"00" ofType:@"mov"]; 
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] 
    initWithContentURL:[NSURL fileURLWithPath:url]]; 

[[NSNotificationCenter defaultCenter] 
    addObserver:self 
    selector:@selector(movieFinishedCallback:) 
    name:MPMoviePlayerPlaybackDidFinishNotification 
    object:player]; 

//---play video in implicit size--- 
player.view.frame = CGRectMake(80, 64, 163, 246); 
[self.view addSubview:player.view]; 

// Hide video controls 
player.controlStyle = MPMovieControlStyleNone; 

//---play movie--- 
[player play]; 

Respuesta

6

Evidentemente, hay un destello negro en la película hasta que se carga suficiente película para que pueda comenzar la reproducción. Aquí está mi solución:

  1. Crear una UIImageView y poner el MPMoviePlayerController en ella. De esta forma puede establecer el alfa en 0.

  2. Tan pronto como llame a [player play]; para reproducir el video, configure un temporizador de .5 segundos.

  3. Cuando se hace el tiempo, cambiar el alfa a 1.

Esto hará que el jugador invisible durante 1/2 segundo (que oculta el flash negro).

+1

Tuve este problema yo también. Pero esta solución es complicada ya que no conoce la hora en que MPMovilePlayerController necesita procesar el video. Por lo tanto, ocultará ciertamente el flash negro pero también el comienzo del video. Una mejor respuesta: http://stackoverflow.com/a/28079496/2327367 – LastMove

2

O simplemente cambiar el color de la vista, que es lo que tu realmente ver ...

player.view.backgroundColor = [UIColor colorWithRed: 1 verde: 1 azul: 1 alfa: 0];

+0

Utilicé [UIColor clearColor] que hace lo mismo, y funcionó perfectamente. Ahora puedo ver UIImageView que tenía en segundo plano y sin flash negro. – christophercotton

+0

no, esto no funcionó – yeahdixon

+0

No funciona en absoluto – jjxtra

1

Para evitar el flash negro, utilice un MPMoviePlayerViewController en lugar de un MPMoviePlayerController. Creo que esta clase crea el fondo en la visualización de la vista, en lugar de la carga de video (como hace MPMoviePlayerController).

Antes de añadir el moviePlayerViewController.moviePlayer.view de vista de la pantalla, hay que añadir un subvista blanco (o una vista secundaria apropiada para su contenido) a la backgroundView, así:

[moviePlayerViewController.moviePlayer.view setFrame:[displayView bounds]]; 

UIView *movieBackgroundView = [[UIView alloc] initWithFrame:[displayView bounds]]; 
movieBackgroundView.backgroundColor = [UIColor whiteColor]; 
[moviePlayerViewController.moviePlayer.backgroundView addSubview:movieBackgroundView]; 
[movieBackgroundView release]; 
2

Creo que la el flash negro puede estar relacionado con la propiedad movieSourceType de MPMoviePlayerController.

Si no lo configura, su valor predeterminado es MPMovieSourceTypeUnknown, lo que hace que la IU se demore hasta que se cargue el archivo.

Trate de añadir esta línea:

player.movieSourceType = MPMovieSourceTypeFile; 

Justo después de la inicialización del jugador.

+0

configuración movieSourceType a MPMovieSourceTypeFile no está ayudando – RainChen

+0

Ya estaba usando SourceType, pero la clave para evitar la pantalla en negro es ponerlo "Justo después de inicializar el reproductor". ¡Gracias! – danielsalare

19

Acabo de tener este problema y lo solucioné agregando un observador al NSNotificationCenter predeterminado para averiguar cuándo la película estaba completamente lista para reproducir, y LUEGO agregué la vista como una subvista a mi vista principal.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkMovieStatus:) name:MPMoviePlayerLoadStateDidChangeNotification object:nil]; 

...

if(moviePlayer.loadState & (MPMovieLoadStatePlayable | MPMovieLoadStatePlaythroughOK)) 
{ 
    [pageShown.view addSubview:moviePlayer.view]; 
    [moviePlayer play]; 
} 
+0

Pensé en algo similar, gracias por acelerar mis ideas ... todas las demás sugerencias anteriores no funcionan para mi código heredado, +1 ~ !! – dklt

+0

aunque, tal vez sería mejor llamar 'play' primero, y luego agregar la subvista? No sé si hay suficiente retraso después de que se convoca el juego, o si ayuda. – Marty

+0

¿Funciona? Intenté esto dos veces y no funciona para mí. – coolcool1994

7

En IOS 6 mpmoviewplayer añade una nueva propiedad: readyForDisplay

esto es lo que estoy jugando con y hasta ahora tan bueno:

  1. crear mpmovieplayer, añadir a escenificar , ocultar it.
  2. añadir notificación de estado de reproducción en la espera movieController
  3. para la displayState en Cambiar y una vez su espectáculo listo el controlador de vídeo:

    - (void)moviePlayerPlayState:(NSNotification *)noti { 
    
    if (noti.object == self.movieController) { 
    
        MPMoviePlaybackState reason = self.movieController.playbackState; 
    
        if (reason==MPMoviePlaybackStatePlaying) { 
    
          [[NSNotificationCenter defaultCenter] removeObserver:self name: MPMoviePlayerPlaybackStateDidChangeNotification object:nil]; 
    
         dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{ 
    
          while (self.movieController.view.hidden) 
          { 
           NSLog(@"not ready"); 
           if (self.movieController.readyForDisplay) { 
    
           dispatch_async(dispatch_get_main_queue(), ^(void) { 
            NSLog(@"show"); 
            self.movieController.view.hidden=NO; 
           }); 
    
           } 
           usleep(50); 
          } 
         }); 
        } 
    
    } 
    

    }

cuando cambia el estado de juego a MPMoviePlaybackStatePlaying comenzamos a verificar que readyDisplayState cambie.

3

Crear vídeo sin addSubview y jugar instrucciones:

NSString *filepath = [[NSBundle mainBundle] pathForResource:@"video" ofType:@"mp4"]; 
    NSURL *fileURL = [NSURL fileURLWithPath:filepath]; 
    MPMoviePlayerController *moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL]; 
    [moviePlayerController.view setFrame:CGRectMake(80, 64, 163, 246)]; 
    moviePlayerController.controlStyle = MPMovieControlStyleNone; 

Preparar vídeo a reproducción y añadirla notificación:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkMovieStatus:) name:MPMoviePlayerLoadStateDidChangeNotification object:nil]; 
    [moviePlayerController prepareToPlay]; 

función Crear checkMovieStatus con addSubview y juegan instrucciones:

- (void)checkMovieStatus:(NSNotification *)notification { 
    if(moviePlayerController.loadState & (MPMovieLoadStatePlayable | MPMovieLoadStatePlaythroughOK)) { 
     [self.view addSubview:moviePlayerController.view]; 
     [moviePlayerController play]; 
    } 
} 
+0

necesita llamar a prepareToPlay para obtener la devolución de llamada MPMoviePlayerLoadSidDanChangeNotification (cambiar desde iOS6?) – Lorenz03Tx

1

Fond solución aquí http://joris.kluivers.nl/blog/2010/01/04/mpmovieplayercontroller-handle-with-care/ desde iOS 6 necesita usar [self.moviePlayer prepareToPlay]; y capture MPMoviePlayerReadyForDisplayDidChangeNotification para usar [self.moviePlayer play];

+0

Esta fue la solución para mí. Usar el evento apropiado parece la forma correcta de abordar este problema, escribiré un tutorial y lo publicaré aquí sobre cómo implementarlo. – newshorts

+0

ACTUALIZACIÓN: aquí hay un enlace a un tutorial que explica esto en más detalle: http: // iwearshorts.com/blog/mpmovieplayercontroller-black-screen-when-fading / – newshorts

Cuestiones relacionadas