define k_THUMBNAIL_IMG_WIDTH 100//縮略圖大小
define k_FPS 1//一秒想取多少幀
//這本來是個(gè)異步調(diào)用,但寫成這種方便大家看和復(fù)制來直接測(cè)試
-
(UIImage)getVideoThumbnailWithUrl:(NSURL)videoUrl second:(CGFloat)second
{
if (!videoUrl)
{
NSLog(@"WARNING:videoUrl為空");
return nil;
}
AVURLAsset *urlSet = [AVURLAsset assetWithURL:videoUrl];
AVAssetImageGenerator *imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlSet];
imageGenerator.appliesPreferredTrackTransform = YES;
imageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;/*
如果不需要獲取縮略圖,就設(shè)置為NO,如果需要獲取縮略圖卢肃,則maximumSize為獲取的最大尺寸茸习。
以BBC為例,getThumbnail = NO時(shí)吃挑,打印寬高數(shù)據(jù)為:19201072储耐。
getThumbnail = YES時(shí)羊初,maximumSize為100100。打印寬高數(shù)據(jù)為:10055.
注:不乘[UIScreen mainScreen].scale,會(huì)發(fā)現(xiàn)縮略圖在100100很虛长赞。
*/
BOOL getThumbnail = YES;
if (getThumbnail)
{
CGFloat width = [UIScreen mainScreen].scale * k_THUMBNAIL_IMG_WIDTH;
imageGenerator.maximumSize = CGSizeMake(width, width);
}
NSError *error = nil;
CMTime time = CMTimeMake(second,k_FPS);
CMTime actucalTime;
CGImageRef cgImage = [imageGenerator copyCGImageAtTime:time actualTime:&actucalTime error:&error];
if (error) {
NSLog(@"ERROR:獲取視頻圖片失敗,%@",error.domain);
}
CMTimeShow(actucalTime);
UIImage *image = [UIImage imageWithCGImage:cgImage];
NSLog(@"imageWidth=%f,imageHeight=%f",image.size.width,image.size.height);
CGImageRelease(cgImage);
return image;
}
原文鏈接:http://www.reibang.com/p/943a1f03ec00
CMTime CMTimeMake (
int64_t value, //表示 當(dāng)前視頻播放到的第幾楨數(shù)
int32_t timescale //每秒的幀數(shù)
);