iOS-合并视频(两个视频和成一个视频)

释放双眼,带上耳机,听听看~!

说明:两个视频合并成一个视频,左边一部分,右边一部分,可以同时播放;类似于软件Sing,仿Sing视频合并

+ (void)convertWithLocalVideoUrl1:(NSURL *)url1 videoUrl2:(NSURL *)url2 half:(BOOL)half progress:(void (^)(CGFloat prog))progress resultURL:(void (^)(NSString *errorCode, NSString *convertUrl))resultURL
{
    //判断本地是否有合成后的视频
    NSString *videoName1 = [[[url1 path] componentsSeparatedByString:@"/"]lastObject];
    NSString *videoName2 = [[[url2 path] componentsSeparatedByString:@"/"]lastObject];
    
    NSString *str = [NSString stringWithFormat:@"%@%@%@.mp4",
                     !half?@"xingyin/":@"",
                     [[videoName1 componentsSeparatedByString:@"."] firstObject],
                     [[videoName2 componentsSeparatedByString:@"."] firstObject]
                     ];
    if ([RequestHelper getCacheDownloadObjectWith:str] != nil && [RequestHelper getCacheDownloadObjectWith:str].length>0) {
        //本地有数据
        resultURL(@"0",[RequestHelper getCacheDownloadObjectWith:str]);
        return;
        
    }
    
    MirrorType type = kMirror4Square;
    NSString *mirrorType = @"MirrorType";
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    [userDefaultes setInteger:type forKey:mirrorType];
    if (half) {
        [userDefaultes setBool:YES forKey:@"kConvertVideo"];
    }else{
        [userDefaultes setBool:NO forKey:@"kConvertVideo"];
    }
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        AVMutableComposition *composition =[AVMutableComposition composition];
        NSMutableArray *audioMixParams = [NSMutableArray array];
        
        //录制的视频1
        AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:url1 options:nil];
        CMTime startTime =CMTimeMakeWithSeconds(0,songAsset.duration.timescale);
        CMTime trackDuration =songAsset.duration;
        //获取视频中的音频素材
        [self setUpAndAddAudioAtPath:url1 toComposition:composition start:startTime dura:trackDuration offset:CMTimeMake(14*44100,44100) andArray:audioMixParams];
        
        //录制的视频2
        AVURLAsset *songAsset1 = [AVURLAsset URLAssetWithURL:url1 options:nil];
        CMTime startTime1 =CMTimeMakeWithSeconds(0,songAsset1.duration.timescale);
        CMTime trackDuration1 =songAsset1.duration;
        //获取视频中的音频素材
        [self setUpAndAddAudioAtPath:url2 toComposition:composition start:startTime1 dura:trackDuration1 offset:CMTimeMake(14*44100,44100) andArray:audioMixParams];
        
        //创建一个可变的音频混合
        AVMutableAudioMix *audioMix =[AVMutableAudioMix audioMix];
        audioMix.inputParameters =[NSArray arrayWithArray:audioMixParams];//从数组里取出处理后的音频轨道参数
        
        //创建一个输出
        AVAssetExportSession *exporter =[[AVAssetExportSession alloc]
                                         initWithAsset:composition
                                         presetName:AVAssetExportPresetAppleM4A];
        exporter.audioMix = audioMix;
        exporter.outputFileType=@"com.apple.m4a-audio";
        
        //视频的声音,合成后存储
        NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES);
        NSString*path=[paths objectAtIndex:0];
        
        NSString *movDirectory = [path stringByAppendingPathComponent:@"/Caches/overMix.mov"];//[path stringByAppendingPathComponent:@"/Caches/com.hackemist.SDWebImageCache.default/overMix.mov"];
    
        if([[NSFileManager defaultManager]fileExistsAtPath:movDirectory]) {
            [[NSFileManager defaultManager]removeItemAtPath:movDirectory error:nil];
        }
        
        NSURL *exportURL =[NSURL fileURLWithPath:movDirectory];
        exporter.outputURL = exportURL;
        
        [exporter exportAsynchronouslyWithCompletionHandler:^{
            //音频合成后
            NSArray *array = [NSArray arrayWithObjects:
                              [url1 relativePath],
                              [url2 relativePath],
                              nil];
            
            [[ExportEffects sharedInstance] setExportProgressBlock: ^(NSNumber *percentage){
                
                //label.text = [NSString stringWithFormat:@"%d%%",(int)([percentage floatValue]*100)];
                //[percentage intValue] == 1.0?[label removeFromSuperview]:label;
                //NSLog(@"percentage = %f",[percentage floatValue]);
                
                progress([percentage floatValue]);
            }];
            [[ExportEffects sharedInstance] setFinishVideoBlock: ^(BOOL success, id result) {
                
                if([[NSFileManager defaultManager]fileExistsAtPath:movDirectory]) {
                    [[NSFileManager defaultManager]removeItemAtPath:movDirectory error:nil];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    resultURL(success?@"0":@"1",success?result:nil);
                    
                });
            }];
            
            [[ExportEffects sharedInstance] addEffectToVideo:array withAudioFilePath:movDirectory half:half];
        }];
    });
}

获取视频中的音频素材

//3.通过文件路径建立和添加音频素材
+ (void)setUpAndAddAudioAtPath:(NSURL*)assetURL toComposition:(AVMutableComposition*)composition start:(CMTime)start dura:(CMTime)dura offset:(CMTime)offset andArray:(NSMutableArray *)audioMixParams{
    
    AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:assetURL options:nil];
    
    AVMutableCompositionTrack *track = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
    AVAssetTrack *sourceAudioTrack = [[songAsset tracksWithMediaType:AVMediaTypeAudio]objectAtIndex:0];
    
    NSError *error = nil;
    BOOL ok = NO;
    
    CMTime startTime = start;
    CMTime trackDuration = dura;
    CMTimeRange tRange =CMTimeRangeMake(startTime,trackDuration);
    
    //设置音量
    //AVMutableAudioMixInputParameters(输入参数可变的音频混合)
    //audioMixInputParametersWithTrack(音频混音输入参数与轨道)
    AVMutableAudioMixInputParameters *trackMix = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:track];
    [trackMix setVolume:0.8f atTime:startTime];
    //素材加入数组
    [audioMixParams addObject:trackMix];
    
    //Insert audio into track  //offsetCMTimeMake(0, 44100)
    ok =  [track insertTimeRange:tRange ofTrack:sourceAudioTrack atTime:kCMTimeInvalid error:&error];
}

ExportEffects类下载地址:http://download.csdn.net/detail/u014220518/9529474

人已赞赏
0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索