Search code examples
iosobjective-cvideoavfoundationsnapchat

How do I correctly use AVPlayer so it doesn't show white screen before playing video?


Every time, when I try to playing a megabyte video using AVPlayer, it initially shows a white screen for a second and then starts the video.

Why is this happening if the video is already cached? Is there a way to stop this from happening, so that it goes straight to the video without displaying a white screen?

I tried using AVPlayer's isReady to check the status of AVPlayer and play video only when it's ready, but it still displays the white screen.

Also every time when I try to get the video duration of the video that's about to play through AVPlayer I keep getting 0.0 seconds initially, so I am not able to add a timer to the video either because I can't get the video duration because it keeps displaying a white screen for a second.


Solution

  • Firstly, AVPlayer doesn't show any white screen, its your background which is white. So, basically your AVPlayer is starting late. I guess you press a UIButton and then it loads the file in AVPlayer and immediately start playing it. Thats where the problem is. It may take some time for the AVPlayer to buffer enough data and be ready to play the file. Using KVO, it is possible to be notified for changes of the player status.

    So first you need to disable the play button, load the AVPlayer and add an observer:

    play.enabled = NO;
    player = [AVPlayer playerWithURL:URL];
    [player addObserver:self forKeyPath:@"status" options:0 context:nil]; 
    

    Then enable it after checking AVPlayerStatusReadyToPlay:

    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
                            change:(NSDictionary *)change context:(void *)context {
        if (object == player && [keyPath isEqualToString:@"status"]) {
            if (player.status == AVPlayerStatusReadyToPlay) {
                play.enabled = YES;
            }
        }
    }