如何替换 MPMoviePlayer 通知?

How do I replace MPMoviePlayer notifications?

在 iOS 9 中,MPMoviePlayer 及其所有组件均已弃用。 我们使用 MPMoviePlayerController 通知,例如 MPMoviePlayerLoadStateDidChangeNotification, MPMovieDurationAvailableNotification, MPMoviePlayerPlaybackStateDidChangeNotification, MPMoviePlayerReadyForDisplayDidChangeNotification,来跟踪视频服务质量。但是现在使用 AVPlayerViewController 我找不到这些通知的正确替代品。

现在如何替换这些通知?

我查看了 MPMoviePlayerNotificationsAVPlayerItemNotifications 的文档,我注意到两件事。

  1. MPMoviePlayerNotifications 不显示它们已被弃用:

  2. AVPlayerItemNotifications 没有任何我能看到的替代品:

所以,我很困惑你说 MPMoviePlayerNotifications 已被弃用,因为文档说它们可用。另外,我不认为 AVPlayerItemNotifications 可以替代 MPMoviePlayerNotifications

AVPlayerViewControllerMPMoviePlayerViewController 的用法有很大不同。您不使用通知,而是使用键值观察来确定与 AVPlayerViewController 关联的 AVPlayer 对象的当前特征。根据文档:

You can observe the status of a player using key-value observing. So that you can add and remove observers safely, AVPlayer serializes notifications of changes that occur dynamically during playback on a dispatch queue. By default, this queue is the main queue (see dispatch_get_main_queue). To ensure safe access to a player’s nonatomic properties while dynamic changes in playback state may be reported, you must serialize access with the receiver’s notification queue. In the common case, such serialization is naturally achieved by invoking AVPlayer’s various methods on the main thread or queue.

例如,如果您想知道播放器何时暂停,请在 AVPlayer 对象的 rate 属性 上添加观察者:

[self.player addObserver:self forKeyPath:@"rate" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context: &PlayerRateContext];

然后在观察方法中检查 new 值是否等于零:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if (context == &PlayerRateContext) {
        if ([[change valueForKey:@"new"] integerValue] == 0) {
            // summon Sauron here (or whatever you want to do)
        }
        return;
    }

    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    return;
}

AVPlayer 上的很多属性都是可观察的。通过 Class reference.

除此之外,还有一些可用于 AVPlayerItem 对象的通知,虽然有限但仍然有用。

Notifications

AVPlayerItemDidPlayToEndTimeNotification

AVPlayerItemFailedToPlayToEndTimeNotification

AVPlayerItemTimeJumpedNotification

AVPlayerItemPlaybackStalledNotification

AVPlayerItemNewAccessLogEntryNotification

AVPlayerItemNewErrorLogEntryNotification

我发现 AVPlayerItemDidPlayToEndTimeNotification 在播放结束后将项目搜索到开头特别有用。

结合使用这两个选项,您应该能够替换 MPMoviePlayerController

的大部分(如果不是全部)通知