player.duration shows always zero in MPMoviePlayerController for video file

柔情痞子 提交于 2019-12-05 01:01:58

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

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

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


 }
Bhavesh Patel

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!