我们使用MPMoviePlayerController通知,如MPMoviePlayerLoadStateDidChangeNotification,MPMovieDurationAvailableNotification,MPMoviePlayerPlaybackStateDidChangeNotification,MPMoviePlayerReadyForDisplayDidChangeNotification,来跟踪视频服务质量.但是现在使用AVPlayerViewController我找不到这些通知的正确替换.
如何立即替换这些通知?
解决方法
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];
然后在observe方法中检查新值是否等于零:
- (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的大部分(如果不是全部)通知