Resume AVPlayer stream playback last sample

怎甘沉沦 提交于 2019-12-06 16:12:50

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.

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;
    }
}

Then, when user wants to re-engage the player, just call -(void)setupPlayer which start the playback from the last live sample.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!