如何替换MPMoviePlayer的通知?

7
在iOS 9中,MPMoviePlayer及其所有组件已被弃用。 我们使用MPMoviePlayerController通知来跟踪视频服务质量,例如MPMoviePlayerLoadStateDidChangeNotification、MPMovieDurationAvailableNotification、MPMoviePlayerPlaybackStateDidChangeNotification和MPMoviePlayerReadyForDisplayDidChangeNotification。但现在使用AVPlayerViewController时,我找不到这些通知的适当替代方法。
现在我该如何替换这些通知呢?
2个回答

8

AVPlayerViewControllerMPMoviePlayerViewController在使用上有很大的区别。你需要使用Key Value Observing来确定与AVPlayerViewController相关联的AVPlayer对象的当前特性,而不是使用通知。根据文档:

您可以使用键值观察来观察播放器的状态。因此,您可以安全地添加和删除观察者,AVPlayer会将动态发生的更改通知序列化到调度队列中进行处理。默认情况下,此队列为主队列(请参见dispatch_get_main_queue)。为了确保在可能报告播放状态中的动态更改时安全访问播放器的非原子属性,您必须使用接收方的通知队列对访问进行序列化。在常见情况下,通过在主线程或队列上调用AVPlayer的各种方法自然地实现这种序列化。

例如,如果您想知道何时暂停播放器,请在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的属性是可以被观察的。请参阅类参考

此外,除了这些属性之外,还有一些针对AVPlayerItem对象的通知可用,虽然数量有限但仍然很有帮助。

通知

AVPlayerItemDidPlayToEndTimeNotification

AVPlayerItemFailedToPlayToEndTimeNotification

AVPlayerItemTimeJumpedNotification

AVPlayerItemPlaybackStalledNotification

AVPlayerItemNewAccessLogEntryNotification

AVPlayerItemNewErrorLogEntryNotification

我特别喜欢使用AVPlayerItemDidPlayToEndTimeNotification,一旦播放结束就将项目定位到开头。

将这两个选项结合使用,您应该能够替换大多数(如果不是全部)MPMoviePlayerController的通知。


你能否提供JWPlayer通知的列表?在网上找不到简明的列表。 - A_G
如何将MPMoviePlayerPlaybackStateDidChangeNotification转换为AVPlayer? - nOOb iOS

1
我查看了MPMoviePlayerNotificationsAVPlayerItemNotifications的文档,发现两件事情。
  1. MPMoviePlayerNotifications没有显示它们已被弃用:

    enter image description here

  2. AVPlayerItemNotifications没有任何可见的替代品:

    enter image description here

所以,我有些困惑,因为你说MPMoviePlayerNotifications已经被弃用了,但文档上说它们仍然可用。另外,我认为AVPlayerItemNotifications没有替代MPMoviePlayerNotifications


2
从文档中:MPMoviePlayerViewController类在iOS 9中正式弃用。(MPMoviePlayerController类也被正式弃用。)为了在iOS 9及更高版本中播放视频内容,应该使用AVKit框架中的AVPictureInPictureController或AVPlayerViewController类,或者使用WebKit中的WKWebView类。我猜这意味着未来不会有MPMoviePlayerNotifications通知。 - Roman Truba

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接