Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 827
Adp Avatar asked Apr 29 '15 05:04

Adp


2 Answers

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;
        }
    }
}
like image 108
blancos Avatar answered Oct 27 '22 11:10

blancos


I know this is an old question, but I get the same issue even when properly detecting when the AVPlayer is ready to play.

I wanted it to play over an image so that there was a smooth transition between an initial static image, and then moving video.

The trick for me was to set a clear background with:

AVPlayerViewController *controller = [[AVPlayerViewController alloc] init];
[controller.view setBackgroundColor:[UIColor clearColor]];

This way, if I toggle the visibility of the player when it's ready to play, I never see a black or white screen, because the player has a clear background, making for a smooth transition!

like image 33
Andre Avatar answered Oct 27 '22 11:10

Andre