Converting CMTime to human readable time in objective-c

| | August 5, 2015

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);

5 Responses to “Converting CMTime to human readable time in objective-c”

  1. here is the code for getting seconds from cmtime

    NSLog(@"seconds = %f", CMTimeGetSeconds(cmTime));
    
  2. You can use CMTimeCopyDescription, it work really well.

    NSString *timeDesc = (NSString *)CMTimeCopyDescription(NULL, self.player.currentTime);
    NSLog(@"Description of currentTime: %@", timeDesc);
    

    edit: okay, i read the question too fast, this is not what your wanted but could be helpful anyway for debuging.

    edit: as @bcattle commented, the implementation i suggested contain a memory leak with ARC. Here the corrected version :

    NSString *timeDesc = (NSString *)CFBridgingRelease(CMTimeCopyDescription(NULL, self.player.currentTime));
    NSLog(@"Description of currentTime: %@", timeDesc);
    
  3. Brody Robertson on November 30, -0001 @ 12:00 AM

    Based on combination of the question and comments above, this is concise:

    AVURLAsset* videoAsset = [AVURLAsset URLAssetWithURL:url options:nil];
    CMTime videoDuration = videoAsset.duration;
    float videoDurationSeconds = CMTimeGetSeconds(videoDuration);
    
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:videoDurationSeconds];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
    [dateFormatter setDateFormat:@"HH:mm:ss"];  //you can vary the date string. Ex: "mm:ss"
    NSString* result = [dateFormatter stringFromDate:date];
    
  4. 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];
    
  5. For example you can use NSDate and it’s description method. You can specify any output format you want.

Leave a Reply