最近做了个小应用,有涉及到本地视频播放及列表显示。
其中一个知识点就是获取本地存储视频,用来界面中的封面显示。
记录如下:
//videoURL:本地视频路径 time:用来控制视频播放的时间点图片截取
-(UIImage*) thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
NSParameterAssert(asset);
AVAssetImageGenerator *assetImageGenerator =[[AVAssetImageGenerator alloc] initWithAsset:asset];
assetImageGenerator.appliesPreferredTrackTransform = YES;
assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
CGImageRef thumbnailImageRef = NULL;
CFTimeInterval thumbnailImageTime = time;
NSError *thumbnailImageGenerationError = nil;
thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)actualTime:NULL error:&thumbnailImageGenerationError];
if(!thumbnailImageRef)
NSLog(@"thumbnailImageGenerationError %@",thumbnailImageGenerationError);
UIImage*thumbnailImage = thumbnailImageRef ? [[UIImage alloc]initWithCGImage: thumbnailImageRef] : nil;
return thumbnailImage;
}
获得的Image直接显示即可。
如果想获取网络图片,只要替换NSURL方式即可。
[NSURL URLWithString:@"network url"]
.PS:
swift实现:
/// 获取本地video的封面截图 /// /// - Parameter url: <#url description#> /// - Returns: <#return value description#> func getVideoFengMian(url:String) -> UIImage { if url.isEmpty { //默认封面图 return UIImage(named: "screenVideo")! } let aset = AVURLAsset(url: URL(fileURLWithPath: url), options: nil) let assetImg = AVAssetImageGenerator(asset: aset) assetImg.appliesPreferredTrackTransform = true assetImg.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels do{ let cgimgref = try assetImg.copyCGImage(at: CMTime(seconds: 10, preferredTimescale: 50), actualTime: nil) return UIImage(cgImage: cgimgref) }catch{ return UIImage(named: "screenVideo")! } }
参数是本地url,可以根据需求自行更改参数等,这里只给个参考。