iOS 某個(gè)時(shí)間段添加特效杰刽,視頻剪切肺然、合并

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;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末指么,一起剝皮案震驚了整個(gè)濱河市酝惧,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌伯诬,老刑警劉巖晚唇,帶你破解...
    沈念sama閱讀 217,509評(píng)論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異盗似,居然都是意外死亡哩陕,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門赫舒,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)悍及,“玉大人,你說(shuō)我怎么就攤上這事接癌⌒母希” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,875評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵扔涧,是天一觀的道長(zhǎng)园担。 經(jīng)常有香客問(wèn)我,道長(zhǎng)枯夜,這世上最難降的妖魔是什么弯汰? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,441評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮湖雹,結(jié)果婚禮上咏闪,老公的妹妹穿的比我還像新娘。我一直安慰自己摔吏,他們只是感情好鸽嫂,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,488評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著征讲,像睡著了一般据某。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上诗箍,一...
    開(kāi)封第一講書(shū)人閱讀 51,365評(píng)論 1 302
  • 那天癣籽,我揣著相機(jī)與錄音,去河邊找鬼滤祖。 笑死筷狼,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的匠童。 我是一名探鬼主播埂材,決...
    沈念sama閱讀 40,190評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼汤求!你這毒婦竟也來(lái)了俏险?” 一聲冷哼從身側(cè)響起严拒,我...
    開(kāi)封第一講書(shū)人閱讀 39,062評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎竖独,沒(méi)想到半個(gè)月后糙俗,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,500評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡预鬓,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,706評(píng)論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了赊颠。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片格二。...
    茶點(diǎn)故事閱讀 39,834評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖竣蹦,靈堂內(nèi)的尸體忽然破棺而出顶猜,到底是詐尸還是另有隱情,我是刑警寧澤痘括,帶...
    沈念sama閱讀 35,559評(píng)論 5 345
  • 正文 年R本政府宣布长窄,位于F島的核電站,受9級(jí)特大地震影響纲菌,放射性物質(zhì)發(fā)生泄漏挠日。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,167評(píng)論 3 328
  • 文/蒙蒙 一翰舌、第九天 我趴在偏房一處隱蔽的房頂上張望嚣潜。 院中可真熱鬧,春花似錦椅贱、人聲如沸懂算。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,779評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)计技。三九已至,卻和暖如春山橄,著一層夾襖步出監(jiān)牢的瞬間垮媒,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,912評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工驾胆, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留涣澡,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,958評(píng)論 2 370
  • 正文 我出身青樓丧诺,卻偏偏與公主長(zhǎng)得像入桂,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子驳阎,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,779評(píng)論 2 354