Joris Kluivers

I like to build software.

MPMoviePlayerController: Handle With Care

Playing videos in an iPhone application requires the usage of the MPMoviePlayerController. This class does require some special care when using it multiple times in a row. By default playing a second movie during a single application run will result in black screen with only sound being played. Other cases will result in the second movie being played with a flickering screen.

The Symptom

The second time a video plays you either see a black or flickering screen.

The Solution

  • Make sure you carefully release the player each time after use.
  • Calling stop before release to prevent the black screen
  • Set the initialPlaybackTime to -1 before release to prevent flickering

The sample code below applies all the above in a small example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
- (void) playMovie {
    MPMoviePlayerController *player = [[MPMoviePlayerController alloc]
        initWithURL:[NSURL URLWithString:@"somefilepath"]];

    if (player) {
        self.moviePlayer = player;
        [player release];

        [[NSNotificationCenter defaultCenter]
            addObserver:self
            selector:@selector(moviePlayerDidFinish:)
            name:MPMoviePlayerPlaybackDidFinishNotification
            object:nil];

        // configure player
        // [..]

        [self.moviePlayer play];
    }
}

- (void)moviePlayerDidFinish:(NSNotification*)notification {
    [[NSNotificationCenter defaultCenter]
        removeObserver:self
        name:MPMoviePlayerPlaybackDidFinishNotification
        object:nil];

    // to prevent a black screen on second play
    [self.moviePlayer stop];
    // to prevent flickering on second play
    self.initialPlaybackTime = -1;

    self.moviePlayer = nil;
}