Objective-C如何使用observeValueForKeyPath检查AVPlayer的状态?

时间:2021-07-19 00:05:02

My current code is:

我目前的代码是:

...
    AVAsset *asset = [AVAsset assetWithURL:video];
    _videoDuration = CMTimeGetSeconds(asset.duration);

    AVPlayerItem *item = [[AVPlayerItem alloc] initWithAsset:asset];
    _player = [[AVPlayer alloc] initWithPlayerItem:item];
    _player.actionAtItemEnd = AVPlayerActionAtItemEndNone;

    [_player addObserver:self
              forKeyPath:@"status"
                 options:0
                 context:nil];
...


- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    if (object == _player && [keyPath isEqualToString:@"status"]) {
        if (_player.status == AVPlayerStatusReadyToPlay) {
            NSLog(@"PLAYING");
        }
    }
}

But for some reason, the observeValueForKeyPath isn't even firing. I was wondering if I did something wrong or if my code is wrong?

但由于某种原因,observeValueForKeyPath甚至没有触发。我想知道我是否做错了或者我的代码是错的?

1 个解决方案

#1


It is theoretically possible for the player's status to change even before your KVO registration which would mean that no further KVO callbacks are made.

理论上,即使在您的KVO注册之前,玩家的状态也可能发生变化,这意味着不会再进行KVO回调。

I would suggest that you add the following option when performing the KVO registering - NSKeyValueObservingOptionInitial. This ensures that you will receive a callback for the initial value as well.

我建议您在执行KVO注册时添加以下选项 - NSKeyValueObservingOptionInitial。这可确保您也将收到初始值的回调。

[_player addObserver:self
          forKeyPath:@"status"
             options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial)
             context:nil];

#1


It is theoretically possible for the player's status to change even before your KVO registration which would mean that no further KVO callbacks are made.

理论上,即使在您的KVO注册之前,玩家的状态也可能发生变化,这意味着不会再进行KVO回调。

I would suggest that you add the following option when performing the KVO registering - NSKeyValueObservingOptionInitial. This ensures that you will receive a callback for the initial value as well.

我建议您在执行KVO注册时添加以下选项 - NSKeyValueObservingOptionInitial。这可确保您也将收到初始值的回调。

[_player addObserver:self
          forKeyPath:@"status"
             options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial)
             context:nil];