ghkaren
ghkaren

Reputation: 601

AVAsset duration is not correct

I have video in Mac player duration of video is 31 seconds. When I'm using it in my app and loading that file the duration of AVAsset is '28.03'.

AVAsset *videoAsset = [AVAsset assetWithURL:videoUrl];
Float64 time = CMTimeGetSeconds(videoAsset.duration);

Upvotes: 6

Views: 3809

Answers (1)

Tomasz Bąk
Tomasz Bąk

Reputation: 6204

For some types of assets a duration is an approximation. If you need the exact duration (should be an extreme case) use:

NSDictionary *options = @{AVURLAssetPreferPreciseDurationAndTimingKey: @YES};
AVURLAsset *videoAsset = [URLAssetWithURL:videoUrl options:options];

You can find more informations in documentation. Calculating the duration may take some time, so remember to use asynchronous loading:

[videoAsset loadValuesAsynchronouslyForKeys:@[@"duration"] completionHandler:^{
    switch ([videoAsset statusOfValueForKey:@"duration" error:nil]) {
        case AVKeyValueStatusLoaded:
            Float64 time = CMTimeGetSeconds(videoAsset.duration);
            // ...
            break;
        default:
            // other cases like cancellation or fail
            break;
    }
}];

You can find some more tips on using AVFoundation API in the video Discovering AV Foundation - WWDC 2010 Session 405

Upvotes: 6

Related Questions