2013-02-07 103 views
19

我需要获取(本地)视频的持续时间,然后才能访问其各个帧,如UIImage s。到目前为止,我一直在使用MPMoviePlayerControlleriOS:获取视频持续时间和缩略图而不播放视频

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

这可以工作,但是即使我没有以任何方式将视频添加到视图(我可以听到在后台播放的音频),视频似乎也开始播放。

有没有什么方法可以在没有实际播放视频的情况下获得视频的持续时间和帧数?

+0

如果要存储在视频文件系统,那么你可以作为[AVAsset]来访问它(https://developer.apple.com/library/mac/#documentation/AVFo undation/Reference/AVAsset_Class/Reference/Reference.html)assetWithUrl:并且返回的AVAsset具有持续时间属性。不知道有关缩略图。 – geraldWilliam

+0

关于这个问题的任何建议:https://stackoverflow.com/questions/47617130/error-getting-same-video-thumbnail-image-every-time-in-swift3-ios/47617794#47617794 –

回答

35

要获取持续时间:

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

要获得framegrab:

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]; 
+0

这确实得到了正确的时间,谢谢。然而,“抢框”时机似乎有点关闭。我不得不使用CMTimeMakeWithSeconds(offsetInSeconds,600)。 –

+0

什么是frameTime?我看到frameTimeStart,应该是frameTime吗? – etayluz

+1

好赶上@etayluz – Shizam

6

调用setShouldAutoPlay:NO确实与在的MPMoviePlayerController招:

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

编辑:我越来越不解释downvoted,但我会通过这个答案站立。如果您需要使用MPMoviePlayerController,那么这将阻止媒体的自动播放,但仍然可以按照我的原始问题获取持续时间和缩略图。

+0

其他人是否同意将自动播放设置为TRUE作为默认设置很愚蠢? – sunny

+1

你的答案的确是,呃,回答这个问题;但我猜你会被拒绝投票,因为你使用'MPMoviePlayerController'所做的是一个丑陋的解决方法,可能会使用比获取所需信息所需资源更多的资源,并可能会在未来的iOS版本中崩溃。你要求系统加载到内存,并准备播放视频,只需要一些关于它的元数据即可。 偏题:只是出于好奇,它显示你谁投票给你吗?我从来没有投过票,所以我很好奇。 – Velociround

8

可以在迅速得到这样

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

请检查此:https://stackoverflow.com/questions/47617130/error-getting-same-video-thumbnail-image-every-time-in-swift3-ios –