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

slo*_*n21 1 iphone avfoundation

self.player = [[AVPlayer playerWithURL:[NSURL URLWithString:@"http://myurl.com/track.mp3"]] retain];
Run Code Online (Sandbox Code Playgroud)

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

Jan*_*les 6

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

AVPlayerItem* playerItem = self.player.currentItem;
[playerItem addObserver:self forKeyPath:kLoadedTimeRanges options:NSKeyValueObservingOptionNew context:playerItemTimeRangesObservationContext];
Run Code Online (Sandbox Code Playgroud)

然后,在观察回调中,您可以理解您传递的数据,如下所示:

-(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];
}
Run Code Online (Sandbox Code Playgroud)

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

-(void)updateVideoAvailable {

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