当我尝试在预滚动后立即播放视频时,我遇到了 AVPlayer 跳过我正在播放的视频的前 0.5 秒的问题。
首先,我创建播放器:
self.videoPlayer = [[AVPlayer alloc] init];
然后,我将播放器项目添加到播放器并添加一个观察者来检查项目何时准备好:
[self.videoPlayer addObserver:self forKeyPath:@"currentItem" options:0 context:kBLCurrentPlayerItemStatusContext];
[self.videoPlayer replaceCurrentItemWithPlayerItem:self.currentVideoPlayerItem];
当观察到播放器项目时,我会检查播放器是否准备好播放。如果它还没有准备好播放,我将添加一个观察者以确保它可以播放:
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
...
} else if (context == kBLCurrentPlayerItemStatusContext) {
[self.videoPlayer removeObserver:self forKeyPath:@"currentItem" context:&kBLCurrentPlayerItemStatusContext];
if ([self.videoPlayer status]==AVPlayerStatusReadyToPlay) {
[self prerollVideoPlayer];
} else {
[self.videoPlayer addObserver:self forKeyPath:@"status" options:0 context:&kBLVideoPlayerStatusContext];
}
}
...
当观察到播放器状态准备好播放时,我会预卷播放器:
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
...
if (context == kBLVideoPlayerStatusContext) {
if ([self.videoPlayer status] == AVPlayerStatusReadyToPlay) {
[self.videoPlayer removeObserver:self forKeyPath:@"status" context:&kBLVideoPlayerStatusContext];
[self prerollVideoPlayer];
}
}
...
前卷完成后,我播放播放器:
-(void)prerollVideoPlayer{
[self.videoPlayer prerollAtRate:1.0 completionHandler:^(BOOL finished){
if (finished) {
[self.videoPlayer play];
}
}];
}
当播放器以这种方式播放时,它会跳过视频的前约 0.5 秒。如果我没有让玩家在完成预滚动后立即播放,我稍后调用 play 方法,它可以正常播放。我已经检查以确保正确观察到所有观察者,并且它们按照我上面提到的顺序发生。是否需要添加另一个观察者或我应该检查的通知以避免这种跳过行为?