iPhone :How to get duration of video selected from library?

21,198

Solution 1

Got the solution : I use AVPlayerItem class and AVFoundation and CoreMedia framework.

#import <AVFoundation/AVFoundation.h>
#import <AVFoundation/AVAsset.h>

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    selectedVideoUrl = [info objectForKey:UIImagePickerControllerMediaURL];

    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:selectedVideoUrl];

    CMTime duration = playerItem.duration;
    float seconds = CMTimeGetSeconds(duration);
    NSLog(@"duration: %.2f", seconds);
}

Solution 2

The other answer to this question using AVPlayerItem didn't work for me, but this did using AVURLAsset:

#import <AVFoundation/AVFoundation.h>

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSURL *videoURL=[info objectForKey:@"UIImagePickerControllerMediaURL"];
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];

    NSTimeInterval durationInSeconds = 0.0;
    if (asset)
        durationInSeconds = CMTimeGetSeconds(asset.duration);
}

Solution 3

Swift 5

regardless of using didFinishPickingMediaWithInfo or didFinishRecordingToOutputFileAtURL you can:

// needed only for didFinishPickingMediaWithInfo
let outputFileURL = info[.mediaURL] as! URL

// get the asset
let asset = AVURLAsset(url: outputFileURL)

// get the time in seconds
let durationInSeconds = asset.duration.seconds

Solution 4

In the event that you use AVFoundation and AssetLibrary frameworks, you can enumerate all assets, apply filter for just videos, and get the duration of each videos with the method - (id)valueForProperty:(NSString *)property. Pass in ALAssetPropertyDuration for property. Code below prints out the following on the console.

video clip number 0 is 66.80833333333334 seconds

video clip number 1 is 190.06 seconds

video clip number 2 is 13.74 seconds

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.

if (!assetItems) {
    assetItems = [[NSMutableArray alloc] init];
} else {
    [assetItems removeAllObjects];
}

if (!assetLibrary) {
    assetLibrary = [[ALAssetsLibrary alloc] init];
}

ALAssetsLibraryGroupsEnumerationResultsBlock listBlock = ^(ALAssetsGroup *group, BOOL *stop) {
    if (group) {
        [group setAssetsFilter:[ALAssetsFilter allVideos]];
        [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
            if (result) {
                [assetItems addObject:result];
                NSString *duration = [result valueForProperty:ALAssetPropertyDuration];
                NSLog(@"video clip number %d is %@ seconds\n",index, duration);
            }
        }];
    }
};

ALAssetsLibraryAccessFailureBlock failBlock = ^(NSError *error) { // error handler block
    NSString *errorTitle = [error localizedDescription];
    NSString *errorMessage = [error localizedRecoverySuggestion];
    NSLog(@"%@...\n %@\n",errorTitle,errorMessage);
};
[assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:listBlock failureBlock:failBlock];
}

Solution 5

Swift 3.0 and Swift 4

let outputFileURL = info[UIImagePickerControllerMediaURL] as! URL
// get the asset
let asset = AVURLAsset.init(url: outputFileURL) // AVURLAsset.init(url: outputFileURL as URL) in swift 3
// get the time in seconds
let durationInSeconds = asset.duration.seconds
print("==== Duration is ",durationInSeconds)
Share:
21,198
Maulik
Author by

Maulik

SOreadytohelp iPhone and iPad developer. :D

Updated on February 01, 2022

Comments

  • Maulik
    Maulik over 2 years

    I am using UIImagePickerController to choose video file from library. And user can upload the video.

    Also I am using videoMaximumDuration property while user wants to capture video and upload it.

    I want to know that How can I get the duration of selected video file ? so that I can restrict the user to upload video that has duration more then 20 seconds.

    I am able to get some basic info about selected video by this code :

    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
    {
        selectedVideoUrl = [info objectForKey:UIImagePickerControllerMediaURL];
        NSError *error;
        NSDictionary * properties = [[NSFileManager defaultManager] attributesOfItemAtPath:selectedVideoUrl.path error:&error];
        NSNumber * size = [properties objectForKey: NSFileSize];
        NSLog(@"Vide info :- %@",properties);
    }
    

    But there is nothing about duration of selected video.

    Thanks...

  • Ethan Allen
    Ethan Allen over 11 years
    You also need to link the CoreMedia framework for CMTimeGetSeconds to work properly.
  • iEinstein
    iEinstein over 10 years
    can we crop a video for particular duration ?
  • iEinstein
    iEinstein over 10 years
    @Maulik- I have seen this but didn't help.
  • Bobjt
    Bobjt almost 10 years
    Getting nan back for an mp4 file...i can get video frames through AVURLAsset however, so I know the file is there and processable in the latter fashion...
  • Ibdakine
    Ibdakine over 8 years
    Scroll to the bottom of this page for a working answer.
  • sudo
    sudo almost 6 years
    You'll get NaN if the URL is invalid.
  • Owais Yusufzai
    Owais Yusufzai over 2 years
    UIImagePickerControllerMediaURL is UIImagePickerController.InfoKey.mediaURL now
  • budiDino
    budiDino over 2 years
    @OwaisYusufzai thanks, I've updated the code to swift 5