如何从NSURL获取AVPlayer iOS4.0的文件大小和当前文件大小

时间:2010-10-22 17:10:38

标签: iphone avfoundation

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

我正在尝试为上述曲目制作UIProgressView。如何从该URL获取文件大小和当前文件大小?请帮忙,谢谢!

3 个答案:

答案 0 :(得分:6)

您需要开始观察当前项的loadedTimeRanges属性,如下所示:

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

然后,在观察回调中,你可以理解你传递的数据:

-(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];
}

然后主线程上的选择器更新进度条,如下所示:

-(void)updateVideoAvailable {

    CMTime playerDuration = [self playerItemDuration];
double duration = CMTimeGetSeconds(playerDuration);
    _videoAvailableBar.progress = _videoAvailable/duration;// this is a UIProgressView
}

答案 1 :(得分:0)

我认为您不想了解文件大小,但您对时间更感兴趣。

在当前播放时间self.player.currentItem.asset.duration的当前时间内尝试self.player.currentTime

答案 2 :(得分:0)

@“loadedTimeRange”是AVPlayerItem类的KVO值。您可以在

中的AVPlayerItem.h文件中找到它的定义
@interface AVPlayerItem (AVPlayerItemPlayability)

类别定义。