Tuesday, April 24, 2012

Transition between 2 movies using a MPMoviePlayerController

I'm trying to make a smooth cross fade between 2 movies in my iPad App. On a button tap the visuals randomize & the movie which is playing fades to the next movie.



Since 2 movies cannot be played simultaneously (from the docs) a straight-forward cross-fade isn't possible. To get around this I use a still image of the initial frame of the new movie (which is to be faded in). I used two players to handle the interchange of movies.



The original movie is paused, Then I transition to the image. Now I add my 2nd movie (with alpha = 0.0) & then transition so that its alpha = 1. I then play the new movie. This all works ok except for a noticeable darkening as the new movie transitions in over the image.



I tested it without the still image & the darkening doesn't seem to occur during said transition.



My code for the switch is below (first half of the if-statement). It looks pretty strange ,looking over it, but it's the method that brought me closest to what I needed.



Maybe there's a better way to go about this task? Thanks in advance :)



- (void) switchMovie;
{

NSURL *movieImageUrl = [movieImageUrlArray objectAtIndex:index];
NSData *data = [NSData dataWithContentsOfURL:movieImageUrl];
UIImage *movieImage = [[UIImage alloc] initWithData:data];
UIImageView *image = [[UIImageView alloc] initWithImage:movieImage];

image.alpha = 0.0f;
[self addSubview:image];

if (moviePlayer1Playing) {

moviePlayer1Playing = NO;
moviePlayer2Playing = NO;

[moviePlayer1 pause]; //pausing later in the method caused a crash, stopping causes a crash.

[UIView animateWithDuration:1.0
delay:0.0
options:UIViewAnimationCurveEaseIn
animations:^{

image.alpha = 1.0f; //fade in still of first frame of new movie

} completion:^(BOOL finished) {

[moviePlayer1 release]; //release original movie.

moviePlayer2 = [[MPMoviePlayerController alloc] initWithContentURL:[movieUrlArray objectAtIndex:index]];

moviePlayer2.shouldAutoplay = NO;
[moviePlayer2 prepareToPlay];
[moviePlayer2 setControlStyle:MPMovieControlStyleNone];
moviePlayer2.scalingMode = MPMovieScalingModeAspectFill;
[moviePlayer2.view setFrame:CGRectMake(0, 0, 1024 , 768)];
moviePlayer2.view.backgroundColor = [UIColor clearColor];
moviePlayer2.view.alpha = 0.0;
[self addSubview:moviePlayer2.view];

[UIView animateWithDuration: 3.0
delay: 0.0
options: UIViewAnimationCurveLinear
animations:^(void){

moviePlayer2.view.alpha = 1.0f;
//During this transition the view goes dark half-way through, before lightening again.

} completion:^ (BOOL finished) {

[moviePlayer2 play];
moviePlayer2Playing = YES;
moviePlayer1Playing = NO;


}];

}];


}




No comments:

Post a Comment