Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS- how to get the duration of .mp4 file by using AVAsset or AVURLAsset

i know duration of video type questions have been answered before but i am facing real trouble in getting duration of an .mp4 file by using AVAsset and by AVURLAsset. i am using Following code

NSString *itemPathString = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0] stringByAppendingPathComponent:obmodel.actualname];
NSURL *itemPathURL = [NSURL URLWithString:itemPathString];

if([[NSFileManager defaultManager] fileExistsAtPath:itemPathString]){

    NSLog(@"File Exists");
}

AVAsset *videoAsset = (AVAsset *)[AVAsset assetWithURL:itemPathURL];
AVAssetTrack *videoAssetTrack = [[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];

NSLog(@"duration: %.2f", CMTimeGetSeconds(videoAssetTrack.timeRange.duration));
if(CMTimeGetSeconds(videoAsset.duration) >= 59.0){
}

but every time it returns 0 i have also imported following headers

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

i have also tried some other code that i know but neither one worked for me. My video is working properly if I play it through iExplorer, my Path is good but don't know whats i'm missing. i would like to share that what i have found is that my AVAssets are not loaded properly please suggest me what should be done.

like image 221
Syed Ali Salman Avatar asked Mar 25 '15 12:03

Syed Ali Salman


1 Answers

Yes, I've had similar problems before. For me the problem went away when I used:

NSURL *itemPathURL = [NSURL fileURLWithPath:itemPathString];

instead of

NSURL *itemPathURL = [NSURL URLWithString:itemPathString];

If you're completely sure your path is ok, this should fix your problem.

Hope this helps!

like image 112
LuisCien Avatar answered Oct 13 '22 01:10

LuisCien