Resume AVPlayer stream playback last sample

若如初见. 提交于 2019-12-08 03:59:52

问题


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.

Is there a way to get the last sample, o configure AVPlayer to reproduce from last sample when tapping on Play Button?


回答1:


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.



来源:https://stackoverflow.com/questions/42386328/resume-avplayer-stream-playback-last-sample

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