iOS: get video duration and thumbnails without playing video

亡梦爱人 提交于 2019-12-03 03:49:44

问题


I need to get a (local) video's duration, and then get access to its individual frames as UIImages. So far I've been using MPMoviePlayerController for this.

First I register for MPMovieDurationAvailableNotification events, and then call prepareToPlay. When the event is received I note the video's duration, and then I request frames via requestThumbnailImagesAtTimes.

This works, however the video seems to start playing even if I have not added the it to the view in any way (I can hear the audio playing in the background).

Is there any way to get a video's duration and frames without actually playing the video?


回答1:


To get the duration:

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

To get a 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];



回答2:


You can get in swift like this

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



回答3:


Calling setShouldAutoPlay:NO does the trick with MPMoviePlayerController:

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

Edit: I'm getting downvoted without explanation, but I'll stand by this answer. If you need to use MPMoviePlayerController then this will prevent autoplay of the media, yet still allow you to get duration and thumbnails as per my original question.



来源:https://stackoverflow.com/questions/14742262/ios-get-video-duration-and-thumbnails-without-playing-video

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