恢复AVPlayer流播放的最后一个样本 [英] Resume AVPlayer stream playback last sample
问题描述
我正在尝试使用本机播放器(AVPlayer)在iOS上重现实时流.但是,我无法恢复播放.当我停止播放并在几秒钟后恢复播放时,播放将从暂停的那一刻开始,而不是重现当前(最后)的实时流样本.
I am trying to use the native player (AVPlayer) to reproduce a live stream on iOS. However, I have trouble resuming the playback. When I stop the playback and resume it after few seconds, the playback starts from the moment I paused instead of reproducing the current (last) sample of the live stream.
是否有一种获取最后一个样本的方法,或者将AVPlayer配置为在点按播放按钮"时从最后一个样本重现?
Is there a way to get the last sample, o configure AVPlayer to reproduce from last sample when tapping on Play Button?
推荐答案
我的解决方案基于拒绝用户保持播放器暂停播放.也就是说,每次重新开始播放时都会破坏播放器.每次创建一个新实例时,都打算恢复播放.
My solution is based on denying user to keep the player paused. This is, destroying the player each time playback is resumed. And creating a new instance each time, playback is intended to be resumed.
根据Apple的建议,知道AVPlayer是否已停止的唯一解决方案是添加KVO.这是:
According to Apple recommendation, the only solution to know if the AVPlayer was stopped is to add KVO. This is:
- (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;
}
}
然后,当用户想要重新与播放器互动时,只需调用-(void)setupPlayer
,该播放器将从上一个实时采样开始播放.
Then, when user wants to re-engage the player, just call -(void)setupPlayer
which start the playback from the last live sample.
这篇关于恢复AVPlayer流播放的最后一个样本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!