player.duration shows always zero in MPMoviePlayer

2019-04-20 10:29发布

问题:

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.

回答1:

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);
    }
}


回答2:

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)
    }


回答3:

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);


 }


回答4:

You can fetch time duration from video file using below code.

NSURL *videoURL = [NSURL fileURLWithPath:VideoFileURL];

AVURLAsset *sourceAsset = [AVURLAsset URLAssetWithURL:videoURL options:nil];

CMTime duration = sourceAsset.duration;

double durationInSeconds = duration.value/duration.timescale;

In durationInSeconds variable you get the exact duration in seconds.