Converting CMTime to human readable time in objective-c

randomor picture randomor · May 18, 2012 · Viewed 31.8k times · Source

So I have a CMTime from a video. How do I convert it into a nice string like in the video time duration label in the Photo App. Is there some convenience methods that handle this? Thanks.

AVURLAsset* videoAsset = [AVURLAsset URLAssetWithURL:url options:nil];
CMTime videoDuration = videoAsset.duration;
float videoDurationSeconds = CMTimeGetSeconds(videoDuration);

Answer

ceekay picture ceekay · Mar 9, 2013

You can use this as well to get a video duration in a text format if you dont require a date format

AVURLAsset *videoAVURLAsset = [AVURLAsset assetWithURL:url];
CMTime durationV = videoAVURLAsset.duration;

NSUInteger dTotalSeconds = CMTimeGetSeconds(durationV);

NSUInteger dHours = floor(dTotalSeconds / 3600);
NSUInteger dMinutes = floor(dTotalSeconds % 3600 / 60);
NSUInteger dSeconds = floor(dTotalSeconds % 3600 % 60);

NSString *videoDurationText = [NSString stringWithFormat:@"%i:%02i:%02i",dHours, dMinutes, dSeconds];