Resume the last example of AVPlayer stream playback
I am trying to use a native player (AVPlayer) to play a live stream on iOS. However, I am unable to resume playback. When I stop playback and resume it after a few seconds, playback starts from the moment it was paused, not to play the current (last) sample of the live stream.
Is there a way to get the latest sample, o configure the AVPlayer to play from the last sample when the play button is clicked?
source to share
My solution is based on user opt-out for the player to pause the action. This destroys the player every time you resume playback. And every time a new instance is created, playback should resume.
According to Apple's recommendation, the only solution to find out if AVPlayer has been stopped is to add KVO. It:
- (void)setupPlayer {
AVPlayer *player = [AVPlayer playerWithURL:streamURL];
AVPlayerViewController *playerViewController = [[AVPlayerViewController alloc] init];
playerViewController.player = player;
self.playerViewController = playerViewController;
[self configureConstraintsForView:self.playerViewController.view]; //Add Player to View
[self setupObservers];
[player play];
}
- (void)setupObservers {
[self.playerViewController.player addObserver:self
forKeyPath:@"rate"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:NULL];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey, id> *)change context:(void *)context
if ([keyPath isEqualToString:@"rate"] && self.playerViewController.player.rate == CGPointZero.x) {
[self.playerViewController.view removeFromSuperview];
[self.playerViewController.player removeObserver:self forKeyPath:@"rate"];
[self.playerViewController.player pause];
self.playerViewController = nil;
}
}
Then, when the user wants to use the player again, simply call -(void)setupPlayer
, which will start playback from the last live sample.
source to share