player.duration在MPMoviePlayerController中为视频文件显示始终为零

Mah*_*abu 11 iphone mpmovieplayercontroller ios

我正在使用此代码在mpmediaplayer控制器中播放一个小视频

MPMoviePlayerController *player = [[MPMoviePlayerController alloc] 
                                   initWithContentURL:[NSURL fileURLWithPath:videostr]]; 
Run Code Online (Sandbox Code Playgroud)

其中videostr是该视频文件的路径.

现在我需要得到该视频文件的长度,因为我正在使用此代码.

length = player.duration;
Run Code Online (Sandbox Code Playgroud)

但它总是显示0.000.但视频播放效果很好.

我正在通过谷歌搜索每个代码来获取视频持续时间player.duration.

我也尝试了其他一些代码

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);
Run Code Online (Sandbox Code Playgroud)

即使它显示为零.任何人都可以帮助我.

预先感谢.

Til*_*ill 22

在内容实际可播放之前,您无法获得有用的持续时间.

注册负载状态更改:

[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(MPMoviePlayerLoadStateDidChange:) 
                                             name:MPMoviePlayerLoadStateDidChangeNotification 
                                           object:nil];
Run Code Online (Sandbox Code Playgroud)

收到通知后评估州:

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