Reputation: 2141
In my iOS app (SDK 5.6), I create an AVURLAsset from a short video, like so:
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:assetURL options:nil];
This seems to work fine. If I examine the asset in gdb, it looks like this:
(gdb) po asset
<AVURLAsset: 0x1a1c40, URL = file://localhost/var/mobile/Applications/A2142D8E-BC19-4E0B-A4C8-ABED4F7D4970/Documents/sample_iTunes.mov>
I use a sample .mov file from the Apple website, stored in the app's Documents directory.
I would like to know the duration of this video, for further processing, but when I examine the duration property, I get this:
(gdb) po asset.duration
There is no member named duration.
What am I doing wrong? Is there any other way to determine the duration of an AVAsset or AVAssetTrack?
TIA: John
Upvotes: 3
Views: 4874
Reputation: 3023
For Swift 3.0 and above
import AVFoundation
let asset = AVAsset(url: URL(fileURLWithPath: ("Your File Path here")!))
let totalSeconds = Int(CMTimeGetSeconds(asset.duration))
let minutes = totalSeconds / 60
let seconds = totalSeconds % 60
let mediaTime = String(format:"%02i:%02i",minutes, seconds)
Upvotes: 1
Reputation: 5187
Creating the asset, however, does not necessarily mean that it’s ready for use. To be used, an asset must have loaded its tracks. Load the asset with
[asset loadValuesAsynchronouslyForKeys:[NSArray arrayWithObject:tracksKey] completionHandler: ^{ // The completion block goes here. }];
And there should be a 'duration' key in the array.
When loading completes, get the duration with
Float64 durationSeconds = CMTimeGetSeconds([<#An asset#> duration]);
Upvotes: 7