there are tons of topics on SO about video preloading but still isn't crystal clear for me.
Objectives:
- Load video from the network, URL is given
- Wait for video loaded completely
- Play video without delay (as I said it's already buffered 100%)
Ideally, calculate download speed, predict f.e when buffered 60% of video, we start playing and 40% will be buffered while playing without delay.
what I tried:
NSURL *url = [NSURL URLWithString:@"video url address here"];
AVURLAsset *avasset = [[AVURLAsset alloc] initWithURL:url options:nil];
AVPlayerItem *item = [[AVPlayerItem alloc] initWithAsset:avasset];
self.player = [[AVPlayer alloc] initWithPlayerItem:item];
self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
CGSize size = self.view.bounds.size;
float x = size.width/2.0-202.0;
float y = size.height/2.0 - 100;
self.playerLayer.frame = CGRectMake(x, y, 404, 200);
self.playerLayer.backgroundColor = [UIColor blackColor].CGColor;
[self.view.layer addSublayer:self.playerLayer];
NSString *tracksKey = @"tracks";
[avasset loadValuesAsynchronouslyForKeys:[NSArray arrayWithObject:tracksKey] completionHandler:
^{
dispatch_async(dispatch_get_main_queue(),
^{
NSError *error = nil;
AVKeyValueStatus status = [avasset statusOfValueForKey:tracksKey error:&error];
NSLog(@"Status %d", status);
if (status == AVKeyValueStatusLoaded) {
[self.player play];
}
else {
NSLog(@"The asset's tracks were not loaded:\n%@", [error localizedDescription]);
}
});
}];
}
Video starts playing and on slow connection hangs out, but if we start playing, let's say after 1 minute, it plays nicely.
The main question - is there ability to get notified when it can be start and play till the end without delaying?
Note: not really important whether it's a AVFoundation or MPMovieController
My assuming that it only can be done by downloading video separately, storing it locally and then playing. Negative aspect there - we can't start playing until whole file is downloaded.
You could key-value observe on the AVPlayerItem's playbackLikelyToKeepUp, playbackBufferEmpty, and playbackBufferFull properties to get a sense of your player's status. See finer details about when these values are true in the docs. Notably: