AVPlayer Item get a nan duration
avplayer, ios, objective-c
Solution
The value of `duration` property will be reported as `kCMTimeIndefinite` until the duration of the underlying asset has been loaded. There are two ways to ensure that the value of duration is accessed only after it becomes available:
Wait until the status of the `AVPlayerItem` is `AVPlayerItemStatusReadyToPlay`.
Register for key-value observation of the `duration` property, requesting the initial value. If the initial value is reported as `kCMTimeIndefinite`, the `AVPlayerItem` will notify you of the availability of the item's duration via key-value observing as soon as its value becomes known.
Problem
I'm playing a file. mp3 from url by stream. I'm using AVPlayer and when I am trying to get the total time to build a progress bar, I get whenever time is nan. ``` NSError *setCategoryError = nil; if ([ [AVAudioSession sharedInstance] isOtherAudioPlaying]) { // mix sound effects with music already playing [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient error:&setCategoryError]; } else { [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&setCategoryError]; } if (setCategoryError) { NSLog(@"Error setting category! %ld", (long)[setCategoryError code]); } NSURL *url = [NSURL URLWithString:@"http://..//46698"]; AVPlayer *player = [AVPlayer playerWithURL:url]; songPlayer=player; [songPlayer addObserver:self forKeyPath:@"status" options:0 context:nil]; - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if (object == songPlayer && [keyPath isEqualToString:@"status"]) { if (songPlayer.status == AVPlayerStatusFailed) { NSLog(@"AVPlayer Failed"); } else if (songPlayer.status == AVPlayerStatusReadyToPlay) { NSLog(@"AVPlayerStatusReadyToPlay"); [songPlayer play]; [songPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time){ CMTime aux = [songPlayer currentTime]; AVPlayerItem *item=[songPlayer currentItem]; CMTime dur=[item duration]; NSLog(@"%f/%f", CMTimeGetSeconds(aux), CMTimeGetSeconds(dur)); }]; } else if (songPlayer.status == AVPlayerItemStatusUnknown) { NSLog(@"AVPlayer Unknown"); } } } ``` I've tried everything. ``` [item duration]; /// Fail [[item asset] duration]; /// Fail ``` and nothing work Anyone know why?