Is KVO possible on AVPlayerItem.loadedTimeRanges?

The apple documentation is referencing it, but how do you set up monitoring for the key value for the property of the loaded TimeRanges object of the AVPlayerItem? This is an NSArray property that does not change, so you cannot just useplayerItem addObserver:self forKeyPath:@"loadedTimeRanges ...

Or is there another way to get notifications or updates whenever this changes?

+5
source share
2 answers

In fact, I use KVO for the loaded TimeRanges without any problems. Maybe you're just not setting the right options? Below is a small modification of some code in Apple AVPlayerDemo , and it works very well for me.

//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]);
    }
}
+6

Right. loadTimeRanges , . ( ) TimeRanges. , .

dispatch_queue_t queue = dispatch_queue_create("playerQueue", NULL);

[player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1)
                                          queue:queue
                                     usingBlock:^(CMTime time) {  
                                         for (NSValue *time in player.currentItem.loadedTimeRanges) {
                                             CMTimeRange range;
                                             [time getValue:&range];
                                             NSLog(@"loadedTimeRanges: %f, %f", CMTimeGetSeconds(range.start), CMTimeGetSeconds(range.duration));
                                         }
                                     }];
+2

All Articles