Search code examples
iosios7avfoundationavplayeravasset

iOS 7 AVPlayer AVPlayerItem duration incorrect in iOS 7


I have the following code in my app:

NSURL *url = [NSURL fileURLWithPath: [self.DocDir stringByAppendingPathComponent: self.FileName] isDirectory: NO];
self.avPlayer = [AVPlayer playerWithURL: url];

Float64 duration = CMTimeGetSeconds(self.avPlayer.currentItem.duration);

This worked fine with iOS 6 but with iOS 7 for some reason it returns NaN. When inspecting self.avPlayer.currentItem.duration the CMTime object has 0's with a flag of 17.

Interestingly the player works fine, just the duration is wrong.

Has anyone else experienced the same issues? I am importing the following:

#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import <CoreMedia/CoreMedia.h>
#import <AVFoundation/AVAsset.h>

Solution

  • After playing around with different ways of initializing the objects I arrived at a working solution:

    AVURLAsset *asset = [AVURLAsset assetWithURL: url];
    Float64 duration = CMTimeGetSeconds(asset.duration);
    AVPlayerItem *item = [AVPlayerItem playerItemWithAsset: asset]; 
    self.avPlayer = [[AVPlayer alloc] initWithPlayerItem: item];
    

    It appears the duration value isn't always immediately available from an AVPlayerItem but it seems to work fine with an AVAsset immediately.