1
self.player = [[AVPlayer playerWithURL:[NSURL URLWithString:@"http://myurl.com/track.mp3"]] retain];

I am trying make a UIProgressView for the above track. How do I obtain the file size and current file size from that URL? Please help, thanks!

Mike Abdullah
  • 14,933
  • 2
  • 50
  • 75
slowman21
  • 2,505
  • 3
  • 20
  • 20

3 Answers3

6

You need to start observing the loadedTimeRanges property of the current item, like this:

AVPlayerItem* playerItem = self.player.currentItem;
[playerItem addObserver:self forKeyPath:kLoadedTimeRanges options:NSKeyValueObservingOptionNew context:playerItemTimeRangesObservationContext];

Then, in the observation callback, you make sense of the data you're passed like this:

-(void)observeValueForKeyPath:(NSString*)aPath ofObject:(id)anObject change:(NSDictionary*)aChange context:(void*)aContext {

if (aContext == playerItemTimeRangesObservationContext) {

    AVPlayerItem* playerItem = (AVPlayerItem*)anObject;
    NSArray* times = playerItem.loadedTimeRanges;

    // there is only ever one NSValue in the array
    NSValue* value = [times objectAtIndex:0];

    CMTimeRange range;
    [value getValue:&range];
    float start = CMTimeGetSeconds(range.start);
    float duration = CMTimeGetSeconds(range.duration);

    _videoAvailable = start + duration; // this is a float property of my VC
    [self performSelectorOnMainThread:@selector(updateVideoAvailable) withObject:nil waitUntilDone:NO];
}

Then the selector on the main thread updates a progress bar, like so:

-(void)updateVideoAvailable {

    CMTime playerDuration = [self playerItemDuration];
double duration = CMTimeGetSeconds(playerDuration);
    _videoAvailableBar.progress = _videoAvailable/duration;// this is a UIProgressView
}
Jane Sales
  • 13,526
  • 3
  • 52
  • 57
0

@"loadedTimeRange" is a KVO value for the AVPlayerItem class. You can find its definition in the AVPlayerItem.h file in the

@interface AVPlayerItem (AVPlayerItemPlayability)

category definition.

Bill
  • 1
0

I think you do not want to know anything about file-sizes, but you're more interested in times.

Try self.player.currentItem.asset.duration for duration of currently playing item, self.player.currentTime for current time.

Michal
  • 4,846
  • 3
  • 33
  • 25
  • Yep, Im making the slider with the duration. But if the user slides pass what is loaded, then bad news. So I want progress of the downloaded/playing track, is that right? Does that make sense? – slowman21 Oct 22 '10 at 22:08
  • I understand, I'm not sure about this, but you might want to enable seeking only within ranges specified in `self.player.currentItem.loadedTimeRanges`. – Michal Oct 23 '10 at 08:49
  • Yea I will need to do that too. But still would be nice for the users to see what has loaded. Like a real streamer. – slowman21 Oct 25 '10 at 14:48
  • Hey Michal, can you explain a little bit how to use loadedTimeRange? I don't know how to get the duration from CMTimeRange. – slowman21 Oct 25 '10 at 20:15