Sam B
Sam B

Reputation: 27598

Video / Movie Duration Time

I have a video saved in apps document dir. What I need to do is find out the duration of video. i.e. how many minutes and seconds long it is. What I cannot figure out is once I have the movie URL what do I need to do to get its duration? Do I use ALAssets? But I am not sure how.

This is the code I have so far

NSString *nameSelected = [NSString stringWithFormat:@"Movie-1.mov"];
    NSLog(@"nameSelected: %@ ...", nameSelected);



    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask ,YES);
    NSString* documentsPath = [paths objectAtIndex:0];
    NSString* movieFile1 = [documentsPath stringByAppendingPathComponent:nameSelected];

    NSURL *firstMovieURL1 = [NSURL fileURLWithPath:movieFile1];

//No sure how I can call this
    //NSString *durationStr = [alAsset valueForProperty:ALAssetPropertyDuration];

Upvotes: 1

Views: 1227

Answers (2)

Sam B
Sam B

Reputation: 27598

this worked for me.

AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:firstMovieURL1
                                                 options:[NSDictionary dictionaryWithObjectsAndKeys:
                                                          [NSNumber numberWithBool:YES],
                                                          AVURLAssetPreferPreciseDurationAndTimingKey,
                                                          nil]];

    NSTimeInterval durationInSeconds = 0.0;
    if (asset) 
        durationInSeconds = CMTimeGetSeconds(asset.duration) ;
    NSLog(@"videoDuration: %.2f", durationInSeconds);

Make sure to import

#import <AssetsLibrary/AssetsLibrary.h>

Upvotes: 4

Shamsudheen TK
Shamsudheen TK

Reputation: 31339

Make use of AVPlayerItem, AVFoundation & CoreMedia frameworks.

AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:yourVideoUrl];
CMTime videoDuration = playerItem.duration;
float seconds = CMTimeGetSeconds(videoDuration);
NSLog(@"videoDuration: %.2f", seconds);

Upvotes: 0

Related Questions