1.美顏蔫缸。大佬的簡(jiǎn)書(shū)---美顏實(shí)現(xiàn)
2.大佬封裝的demo (https://github.com/Dongdong1991/GPURenderKitDemo/blob/master)
//開(kāi)始進(jìn)行濾鏡渲染
-(void)saveEffectVideoActionWithPlayURL:(NSURL *)url outPutFilter: (GPUImageOutput<GPUImageInput> *)outPutFilter leftTime:(float)leftTime rightTime: (float)rightTime callback:(void(^)(NSURL *outUrlPath))callBack {
self.effectProgressEnd = callBack;
self.leftTime = leftTime;
self.rightTime = rightTime;
// 要轉(zhuǎn)換的視頻
//
_movieFile = [[GPUImageMovie alloc] initWithURL:url];
_movieFile.runBenchmark = YES;
_movieFile.playAtActualSpeed = NO;
// 創(chuàng)建濾鏡
[_movieFile addTarget:outPutFilter];
// 設(shè)置輸出路徑
NSString * pathToMovie = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Movie.mp4"];
// - 如果文件已存在,AVAssetWriter不允許直接寫進(jìn)新的幀,所以會(huì)刪掉老的視頻文件
unlink([pathToMovie UTF8String]);
self.movieURL = [NSURL fileURLWithPath:pathToMovie];
// 輸出 后面的size可改 ~ 現(xiàn)在來(lái)說(shuō)480*640有點(diǎn)太差勁了
AVAsset *asset = [AVAsset assetWithURL:url];
NSArray *tracks = [asset tracksWithMediaType:AVMediaTypeVideo];
AVAssetTrack *videoTrack = [tracks objectAtIndex:0];
// CGAffineTransform t = videoTrack.preferredTransform;//這里的矩陣有旋轉(zhuǎn)角度,轉(zhuǎn)換一下即可
NSLog(@"=====hello width:%f===height:%f",videoTrack.naturalSize.width,videoTrack.naturalSize.height);//寬高
_movieWriter = [[GPUImageMovieWriter alloc] initWithMovieURL:self.movieURL size:videoTrack.naturalSize];
[outPutFilter addTarget:_movieWriter];
_movieWriter.shouldPassthroughAudio = YES;
_movieFile.audioEncodingTarget = _movieWriter;
[_movieFile enableSynchronizedEncodingUsingMovieWriter:_movieWriter];
// 完成之后的回調(diào) - 為啥100%了之后還會(huì)待一會(huì)才調(diào)用這個(gè)completeBlock
@weakify(self);
[self.movieWriter setCompletionBlock:^{
@strongify(self);
[outPutFilter removeTarget:self.movieWriter];
[self.movieWriter finishRecording];
NSLog(@"_movieWriter_成功");
// if (callBack) {
// callBack(strongSelf.movieURL);
// }
// // 異步寫入相冊(cè)
// dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// dispatch_async(concurrentQueue, ^{
// [strongSelf saveVideo:strongSelf.movieURL];
// });
[self cutVideo];
}];
[self.movieWriter setFailureBlock:^(NSError *error) {
@strongify(self);
NSLog(@"_movieWriter_失敗");
if (self.effectProgressEnd) {
self.effectProgressEnd([NSURL fileURLWithPath:@""]);
}
}];
[self.movieWriter startRecording];
[_movieFile startProcessing];
}
//剪切視頻
- (void)cutVideo {
//視頻總長(zhǎng)
float videoTimeLang = [JWVideoEditManage getMediaDurationWithMediaUrl:self.videoPath];
//第一次截取視頻資源
if (_leftTime >1) {
AVMutableComposition *composition = [self getAVMutableCompositionWithLeftTime:0 rightTime:_leftTime videoURL:self.videoPath];
[self.compositionDic setObject:composition forKey:@"firstComposition"];
} else {
_leftTime = 0;
}
//第二次截取視頻資源
_rightTime = _rightTime + 1 > videoTimeLang ? videoTimeLang : _rightTime;
AVMutableComposition *composition = [self getAVMutableCompositionWithLeftTime:_leftTime rightTime:_rightTime videoURL:self.videoPath];
[self.compositionDic setObject:composition forKey:@"secondComposition"];
//第三次截取視頻資源
if (videoTimeLang > _rightTime + 1) {
AVMutableComposition *composition = [self getAVMutableCompositionWithLeftTime:_rightTime rightTime:videoTimeLang videoURL:self.videoPath];
[self.compositionDic setObject:composition forKey:@"thirdComposition"];
}
if (self.compositionDic[@"secondComposition"]) {
AVMutableComposition *composition = [self getAVMutableCompositionWithLeftTime:self.leftTime rightTime:self.rightTime videoURL:self.movieURL];
self.compositionDic[@"secondComposition"] = composition;
}
dispatch_async(dispatch_get_main_queue(), ^{
[self combVideos];
});
}
///根據(jù)URL 將視頻資源轉(zhuǎn)化為composition
- (AVMutableComposition *)getAVMutableCompositionWithLeftTime:(float)leftTime rightTime:(float)rightTime videoURL:(NSURL *)videoURL {
NSDictionary *optDict = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
AVAsset *firstAsset = [[AVURLAsset alloc] initWithURL:videoURL options:optDict];
TimeRange timeRange = {leftTime, rightTime - leftTime};
//由于沒(méi)有計(jì)算當(dāng)前CMTime的起始位置际起,現(xiàn)在插入0的位置,所以合并出來(lái)的視頻是后添加在前面拾碌,可以計(jì)算一下時(shí)間,插入到指定位置
//CMTimeRangeMake 指定起去始位置
// CMTimeRange firstTimeRange = CMTimeRangeMake(kCMTimeZero, firstAsset.duration);
//開(kāi)始位置startTime
CMTime startTime = CMTimeMakeWithSeconds(timeRange.location, firstAsset.duration.timescale);
//截取長(zhǎng)度videoDuration
CMTime videoDuration = CMTimeMakeWithSeconds(timeRange.length, firstAsset.duration.timescale);
CMTimeRange videoTimeRange = CMTimeRangeMake(startTime, videoDuration);
AVMutableComposition *composition = [AVMutableComposition composition];
//為視頻類型的的Track
AVMutableCompositionTrack *compositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
[compositionTrack insertTimeRange:videoTimeRange ofTrack:[firstAsset tracksWithMediaType:AVMediaTypeVideo][0] atTime:kCMTimeZero error:nil];
//只合并視頻加叁,導(dǎo)出后聲音會(huì)消失倦沧,所以需要把聲音插入到混淆器中
//添加音頻,添加本地其他音樂(lè)也可以,與視頻一致
AVMutableCompositionTrack *audioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
[audioTrack insertTimeRange:videoTimeRange ofTrack:[firstAsset tracksWithMediaType:AVMediaTypeAudio][0] atTime:kCMTimeZero error:nil];
return composition;
}
///合并視頻資源
- (void)combVideos {
AVMutableComposition *firstComposition = self.compositionDic[@"firstComposition"];
AVMutableComposition *secondComposition = self.compositionDic[@"secondComposition"];
AVMutableComposition *thirdComposition = self.compositionDic[@"thirdComposition"];
// NSDictionary *optDict = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
// AVAsset *firstAsset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:self.videoPath] options:optDict];
// AVAsset *secondAsset = [[AVURLAsset alloc] initWithURL:<#(nonnull NSURL *)#> options:<#(nullable NSDictionary<NSString *,id> *)#>];
AVMutableComposition *composition = [AVMutableComposition composition];
//為視頻類型的的Track
AVMutableCompositionTrack *compositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
//倒序插入
if (thirdComposition) {
//現(xiàn)在插入0的位置,所以合并出來(lái)的視頻是后添加在前面,可以計(jì)算一下時(shí)間它匕,插入到指定位置
//CMTimeRangeMake 指定起去始位置
CMTimeRange timeRange = CMTimeRangeMake(kCMTimeZero, thirdComposition.duration);
[compositionTrack insertTimeRange:timeRange ofTrack:[thirdComposition tracksWithMediaType:AVMediaTypeVideo][0] atTime:kCMTimeZero error:nil];
//只合并視頻展融,導(dǎo)出后聲音會(huì)消失,所以需要把聲音插入到混淆器中
//添加音頻,添加本地其他音樂(lè)也可以,與視頻一致
// AVMutableCompositionTrack *audioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
// [audioTrack insertTimeRange:timeRange ofTrack:[thirdComposition tracksWithMediaType:AVMediaTypeAudio][0] atTime:kCMTimeZero error:nil];
}
if (secondComposition) {
//現(xiàn)在插入0的位置,所以合并出來(lái)的視頻是后添加在前面豫柬,可以計(jì)算一下時(shí)間告希,插入到指定位置
//CMTimeRangeMake 指定起去始位置
CMTimeRange timeRange = CMTimeRangeMake(kCMTimeZero, secondComposition.duration);
[compositionTrack insertTimeRange:timeRange ofTrack:[secondComposition tracksWithMediaType:AVMediaTypeVideo][0] atTime:kCMTimeZero error:nil];
//添加音頻
// AVMutableCompositionTrack *audioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
// [audioTrack insertTimeRange:timeRange ofTrack:[secondComposition tracksWithMediaType:AVMediaTypeAudio][0] atTime:kCMTimeZero error:nil];
}
if (firstComposition) {
//現(xiàn)在插入0的位置,所以合并出來(lái)的視頻是后添加在前面,可以計(jì)算一下時(shí)間烧给,插入到指定位置
//CMTimeRangeMake 指定起去始位置
CMTimeRange timeRange = CMTimeRangeMake(kCMTimeZero, firstComposition.duration);
[compositionTrack insertTimeRange:timeRange ofTrack:[firstComposition tracksWithMediaType:AVMediaTypeVideo][0] atTime:kCMTimeZero error:nil];
//添加音頻
// AVMutableCompositionTrack *audioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
// [audioTrack insertTimeRange:timeRange ofTrack:[firstComposition tracksWithMediaType:AVMediaTypeAudio][0] atTime:kCMTimeZero error:nil];
}
//
[self addAudioCompositionTrack:composition videoURL:self.videoPath];
NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/output_comb_%@.mp4",[self getNowTimeTimestamp2]]];
// NSString *filePath = [cachePath stringByAppendingPathComponent:@"comp.mp4"];
AVAssetExportSession *exporterSession = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetHighestQuality];
exporterSession.outputFileType = AVFileTypeMPEG4;
exporterSession.outputURL = [NSURL fileURLWithPath:filePath]; //如果文件已存在燕偶,將造成導(dǎo)出失敗
exporterSession.shouldOptimizeForNetworkUse = YES; //用于互聯(lián)網(wǎng)傳輸
[exporterSession exportAsynchronouslyWithCompletionHandler:^{
switch (exporterSession.status) {
case AVAssetExportSessionStatusUnknown:
NSLog(@"exporter Unknow");
if (self.effectProgressEnd) {
self.effectProgressEnd([NSURL fileURLWithPath:@""]);
}
break;
case AVAssetExportSessionStatusCancelled:
NSLog(@"exporter Canceled");
if (self.effectProgressEnd) {
self.effectProgressEnd([NSURL fileURLWithPath:@""]);
}
break;
case AVAssetExportSessionStatusFailed:
NSLog(@"exporter Failed");
if (self.effectProgressEnd) {
self.effectProgressEnd([NSURL fileURLWithPath:@""]);
}
break;
case AVAssetExportSessionStatusWaiting:
NSLog(@"exporter Waiting");
break;
case AVAssetExportSessionStatusExporting:
NSLog(@"exporter Exporting");
// [self saveVideo:[NSURL fileURLWithPath:filePath]];
break;
case AVAssetExportSessionStatusCompleted:
NSLog(@"exporter Completed");
[self saveVideo:[NSURL fileURLWithPath:filePath]];
if (self.effectProgressEnd) {
self.effectProgressEnd([NSURL fileURLWithPath:filePath]);
}
break;
}
}];
}
//: 添加聲音 軌道 只保留原來(lái)視頻聲音
/**
添加聲音 軌道,
@param mixComposition 合成器
@param asset 源
@param timeRange 視頻返回
*/
- (void)addAudioCompositionTrack:(AVMutableComposition *)mixComposition videoURL:(NSURL *)videoURL{
NSDictionary *optDict = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
AVAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:optDict];
//音頻采集compositionCommentaryTrack
//atTime插放在視頻的時(shí)間位置
NSError * error = nil;
//這里采用信號(hào)量加鎖础嫡,是聲音轉(zhuǎn)換完成之后繼續(xù)進(jìn)行合成視頻
dispatch_semaphore_t t = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
AVAssetTrack *audioAssetTrack = [[asset tracksWithMediaType:AVMediaTypeAudio] firstObject];
AVMutableCompositionTrack * audioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
// 加入合成軌道之中
CMTimeRange audioTimeRange = CMTimeRangeMake(kCMTimeZero, asset.duration);
//插入音頻
[audioTrack insertTimeRange:audioTimeRange ofTrack:audioAssetTrack atTime:CMTimeMakeWithSeconds(0, asset.duration.timescale) error:nil];
dispatch_semaphore_signal(t);
});
dispatch_semaphore_wait(t, DISPATCH_TIME_FOREVER);
NSLog(@"error---%@",error);
}
-(NSString *)getNowTimeTimestamp2 {
NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
NSTimeInterval a=[dat timeIntervalSince1970];
NSString*timeString = [NSString stringWithFormat:@"%0.f", a];//轉(zhuǎn)為字符型
return timeString;
}