為視頻添加濾鏡效果的思路如下
1.使用AVPlayer + CIFilter進(jìn)行渲染
參考文檔 Processing Video with AV Foundation
關(guān)鍵代碼
//1
AVURLAsset *asset1 = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sample_clip1" ofType:@"m4v"]]];
//2
CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
AVVideoComposition *composition1 = [AVVideoComposition videoCompositionWithAsset:asset1 applyingCIFiltersWithHandler:^(AVAsynchronousCIImageFilteringRequest * _Nonnull request) {
//3
CIImage *source = request.sourceImage.imageByClampingToExtent;
int currentTime = request.compositionTime.value / request.compositionTime.timescale;
if (currentTime < 3) {
[request finishWithImage:source context:nil];
} else {
[filter setValue:source forKey:kCIInputImageKey];
//4
CIImage *output = [filter.outputImage imageByCroppingToRect:request.sourceImage.extent];
[request finishWithImage:output context:nil];
}
}];
//5
AVPlayerItem *item = [[AVPlayerItem alloc] initWithAsset:asset1];
item.videoComposition = composition;
步驟1:讀取本地的視頻路徑
步驟2:設(shè)置CIFilter效果趁尼,使用AVVideoComposition處理渲染過(guò)程
步驟3:獲取視頻幀并轉(zhuǎn)換成CIImage以供CIFilter進(jìn)行渲染,可以設(shè)定渲染的時(shí)間
步驟4:將渲染完成的CIImage返還給request
步驟5:將視頻組成裝入播放文件中播放即可
存在問(wèn)題:
1.播放與導(dǎo)出時(shí)加入濾鏡的情況下cpu占用100%
實(shí)例參見(jiàn) github Demo