iOS:获取video持续时间和缩略图,无需播放video

我需要获取(本地)video的持续时间,然后以UIImage的身份访问其各个帧。 到目前为止,我一直在使用MPMoviePlayerController

首先,我注册了MPMovieDurationAvailableNotification事件,然后调用prepareToPlay 。 当收到事件时,我注意到video的持续时间,然后通过requestThumbnailImagesAtTimes请求帧。

这是有效的,但是video似乎开始播放,即使我没有以任何方式将它添加到视图(我可以听到在后台播放的audio)。

有没有什么方法可以在没有真正播放video的情况下获得video的持续时间和帧数?

要获得持续时间:

 NSURL *sourceMovieURL = [NSURL fileURLWithPath:somePath]; AVURLAsset *sourceAsset = [AVURLAsset URLAssetWithURL:sourceMovieURL options:nil]; CMTime duration = sourceAsset.duration; 

要获取框架:

 AVAssetImageGenerator* generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:destinationAsset]; //Get the 1st frame 3 seconds in int frameTimeStart = 3; int frameLocation = 1; //Snatch a frame CGImageRef frameRef = [generator copyCGImageAtTime:CMTimeMake(frameTimeStart,frameLocation) actualTime:nil error:nil]; 

你可以像这样迅速得到

 func getMediaDuration(url: NSURL!) -> Float64{ let asset : AVURLAsset = AVURLAsset(URL: url) as AVURLAsset let duration : CMTime = asset.duration return CMTimeGetSeconds(duration) } 

调用setShouldAutoPlay:NO没有与MPMoviePlayerController的伎俩:

  moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL: movieURL]; [moviePlayerController setShouldAutoplay:NO]; [moviePlayerController prepareToPlay]; 

编辑:我得到downvoted没有解释,但我会支持这个答案。 如果你需要使用MPMoviePlayerController那么这将阻止媒体的自动播放,但仍然可以让你得到持续时间和缩略图,根据我原来的问题。