AVVlayerItem.loadedTimeRanges上的KVO可能吗?

Chr*_*s C 5 key-value-observing avfoundation ios avplayer

苹果文档提到了它,但是如何为AVPlayerItem的loadedTimeRanges属性设置键值观察?该属性是一个不会改变的NSArray,所以你不能只使用它playerItem addObserver:self forKeyPath:@"loadedTimeRanges ...

或者是否有其他方法可以在此更改时收到通知或更新?

Kev*_*vin 7

实际上,我正在使用KVO for loadedTimeRanges而没有任何麻烦.也许你只是没有设置正确的选项?以下是对Apple AVPlayerDemo中某些代码的一个非常小的修改,它对我来说非常好用.

//somewhere near the top of the file
NSString * const kLoadedTimeRangesKey   = @"loadedTimeRanges";
static void *AudioControllerBufferingObservationContext = &AudioControllerBufferingObservationContext;


- (void)someFunction
{  
    // ...

    //somewhere after somePlayerItem has been initialized
    [somePlayerItem addObserver:self
                       forKeyPath:kLoadedTimeRangesKey
                          options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
                          context:AudioControllerBufferingObservationContext];

    // ...
}

- (void)observeValueForKeyPath:(NSString*) path 
                  ofObject:(id)object 
                    change:(NSDictionary*)change 
                   context:(void*)context
{
    if (context == AudioControllerBufferingObservationContext)
    {
        NSLog(@"Buffering status: %@", [object loadedTimeRanges]);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 事实证明,我可以为loadedTimeRanges工作的唯一选择是NSKeyValueObservingOptionInitial.我的工作是在屏幕上显示UIProgressView时使用Timer(实际上是CADisplayLink)来检查loadedTimeRanges属性.这有效,但对我来说似乎很蹩脚.我宁愿KVO任何新的价值观. (2认同)
  • 我发现和Chris L.一样令人沮丧,它第一次工作,但在我更改播放器项目后,我得到每个回调_but_ loadedTimeRanges (2认同)