Mahesh Babu Mahesh Babu - 5 months ago 44
iOS Question

player.duration shows always zero in MPMoviePlayerController for video file

I am playing a small video in mpmediaplayer controller using this code

MPMoviePlayerController *player = [[MPMoviePlayerController alloc]
initWithContentURL:[NSURL fileURLWithPath:videostr]];

where videostr is path of that video file.

Now i need to get length of that video file for that i am using this code.

length = player.duration;

But it always shows 0.000. But the video is playing well.

I am checking by googling every where code to get video duration is

And i try some other code also

AVURLAsset *asset = [[[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:videostr]
options:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], AVURLAssetPreferPreciseDurationAndTimingKey, nil]] autorelease];
NSTimeInterval duration;
if (asset)
duration = CMTimeGetSeconds(asset.duration) ;
NSLog(@">>>>>>>>>>>>>>>>>>>> %f", asset.duration);

even though it shows zero.Can any one please help me.

Thank in advance.


You can not get a useful duration until the content is actually playable.

Register for load state changes:

[[NSNotificationCenter defaultCenter] addObserver:self 

Evaluate the state once being notified:

- (void)MPMoviePlayerLoadStateDidChange:(NSNotification *)notification
    if ((player.loadState & MPMovieLoadStatePlaythroughOK) == MPMovieLoadStatePlaythroughOK)
        NSLog(@"content play length is %g seconds", player.duration);