现在 MPMoviePlayerPlaybackDidFinishReasonUserInfoKey 已被弃用,找到播放结束原因的最佳方法是什么?

Now that MPMoviePlayerPlaybackDidFinishReasonUserInfoKey is deprecated, what is the best way to find why playback ended?

在 iOS9 中,MPMoviePlayer 类 已全部弃用,取而代之的是 AVPlayer。我有一个现有的应用程序使用 MPMoviePlayerPlaybackDidFinishReasonUserInfoKey 来确定如何记录有关视频播放器如何结束的事件。我如何使用 AVPlayer 做同样的事情?

以下是结束原因键:

试试,在viewDidLoad:

    AVPlayerItem* playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:@"yoururl"]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:playerItem];

    AVPlayer* player = [[[AVPlayer alloc] initWithPlayerItem:playerItem] autorelease];

    [player play]

-(void)itemDidFinishPlaying:(NSNotification *) notification {
    // Will be called when AVPlayer finishes playing playerItem
}

AVKit 中没有与 MPMoviePlayerPlaybackDidFinishReasonUserInfoKey 和 MPMoviePlayerPlaybackDidFinishNotification 等价的东西。要在 AVKit 中完成相同的功能,您必须分别收听三个通知,而不是一个可能原因不同的通知。

  • MPMovieFinishReasonPlaybackEnded >>> AVPlayerItemDidPlayToEndTimeNotification
  • MPMovieFinishReasonPlaybackError >>> AVPlayerItemFailedToPlayToEndTimeNotification
  • MPMovieFinishReasonUserExited。没有转换。有多种方法可以检测用户是否杀死了玩家。一个是检测模态已关闭。

如果你想知道视频是否在播放,你可以做一个KVO:

[self.player addObserver:self forKeyPath:@"rate" options:0 context:nil];

然后添加这个方法:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context 
{
    if ([keyPath isEqualToString:@"rate"]) {
        if ([self.player rate]) {
            [self changeToPause];  // This changes the button to Pause
        }
        else {
            [self changeToPlay];   // This changes the button to Play
        }
    }
}