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.
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);
}
}
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)
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With