Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 player.duration only.

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.

like image 297
Mahesh Babu Avatar asked Jan 27 '12 15:01

Mahesh Babu


3 Answers

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

Register for load state changes:

[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(MPMoviePlayerLoadStateDidChange:) 
                                             name:MPMoviePlayerLoadStateDidChangeNotification 
                                           object:nil];

Evaluate the state once being notified:

- (void)MPMoviePlayerLoadStateDidChange:(NSNotification *)notification
{
    if ((player.loadState & MPMovieLoadStatePlaythroughOK) == MPMovieLoadStatePlaythroughOK)
    {
        NSLog(@"content play length is %g seconds", player.duration);
    }
}
like image 155
Till Avatar answered Nov 02 '22 23:11

Till


SWIFT

You can do in swift like this

func getMediaDuration(url: NSURL!) -> Float64{
        var asset : AVURLAsset = AVURLAsset.assetWithURL(url) as AVURLAsset
        var duration : CMTime = asset.duration
        
        return CMTimeGetSeconds(duration)
    }
like image 23
Dharmbir Singh Avatar answered Nov 03 '22 00:11

Dharmbir Singh


use MPMovieDurationAvailableNotification

[[NSNotificationCenter defaultCenter] addObserver:self 
                                     selector:@selector(movieDurationAvailable:) 
                                         MPMovieDurationAvailableNotification object:nil];

- (void)movieDurationAvailable:(NSNotification *)notification {

        NSLog(@"content play length is %g seconds", moviePlayer.duration);


 }
like image 40
amena Avatar answered Nov 03 '22 01:11

amena