iOS合并多个视频(Obj-c&Swift)

0x00 写在前面

  1. 需求是把两个或多个小视频合并成一个视频
  2. 合并效果为首尾相接,不是视频重叠
  3. 当前代码为示例代码,只展示了合并两个视频文件,要实现多个视频文件合并为一个,需要改动代码

0x01 代码展示(Obj-c&Swift)

//Obj-c
- (void)combVideos {
    NSBundle *mainBundle = [NSBundle mainBundle];
    NSString *firstVideo = [mainBundle pathForResource:@"1" ofType:@"mp4"];
    NSString *secondVideo = [mainBundle pathForResource:@"2" ofType:@"mp4"];
    
    NSDictionary *optDict = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVAsset *firstAsset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:firstVideo] options:optDict];
    AVAsset *secondAsset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:secondVideo] options:optDict];
    
    AVMutableComposition *composition = [AVMutableComposition composition];
    //为视频类型的的Track
    AVMutableCompositionTrack *compositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
    //由于没有计算当前CMTime的起始位置,现在插入0的位置,所以合并出来的视频是后添加在前面,可以计算一下时间,插入到指定位置
    //CMTimeRangeMake 指定起去始位置
    CMTimeRange firstTimeRange = CMTimeRangeMake(kCMTimeZero, firstAsset.duration);
    CMTimeRange secondTimeRange = CMTimeRangeMake(kCMTimeZero, secondAsset.duration);
    [compositionTrack insertTimeRange:secondTimeRange ofTrack:[secondAsset tracksWithMediaType:AVMediaTypeVideo][0] atTime:kCMTimeZero error:nil];
    [compositionTrack insertTimeRange:firstTimeRange ofTrack:[firstAsset tracksWithMediaType:AVMediaTypeVideo][0] atTime:kCMTimeZero error:nil];
    
    //只合并视频,导出后声音会消失,所以需要把声音插入到混淆器中
    //添加音频,添加本地其他音乐也可以,与视频一致
    AVMutableCompositionTrack *audioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
    [audioTrack insertTimeRange:secondTimeRange ofTrack:[firstAsset tracksWithMediaType:AVMediaTypeAudio][0] atTime:kCMTimeZero error:nil];
    [audioTrack insertTimeRange:firstTimeRange ofTrack:[firstAsset tracksWithMediaType:AVMediaTypeAudio][0] atTime:kCMTimeZero error:nil];
    
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [cachePath stringByAppendingPathComponent:@"comp.mp4"];
    AVAssetExportSession *exporterSession = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetHighestQuality];
    exporterSession.outputFileType = AVFileTypeMPEG4;
    exporterSession.outputURL = [NSURL fileURLWithPath:filePath]; //如果文件已存在,将造成导出失败
    exporterSession.shouldOptimizeForNetworkUse = YES; //用于互联网传输
    [exporterSession exportAsynchronouslyWithCompletionHandler:^{
        switch (exporterSession.status) {
            case AVAssetExportSessionStatusUnknown:
                NSLog(@"exporter Unknow");
                break;
            case AVAssetExportSessionStatusCancelled:
                NSLog(@"exporter Canceled");
                break;
            case AVAssetExportSessionStatusFailed:
                NSLog(@"exporter Failed");
                break;
            case AVAssetExportSessionStatusWaiting:
                NSLog(@"exporter Waiting");
                break;
            case AVAssetExportSessionStatusExporting:
                NSLog(@"exporter Exporting");
                break;
            case AVAssetExportSessionStatusCompleted:
                NSLog(@"exporter Completed");
                break;
        }
    }];
}

Swift代码:需要先导入 import AVFoundation
*Swift版本注释可参考Obj-c版本*

func combVideos() {
        let firstVideo = NSBundle.mainBundle().pathForResource("1", ofType: "mp4")
        let secondVideo = NSBundle.mainBundle().pathForResource("2", ofType: "mp4")

        let optDict = [AVURLAssetPreferPreciseDurationAndTimingKey : NSNumber(bool: false)]
        let firstAsset = AVURLAsset(URL: NSURL(fileURLWithPath: firstVideo!), options: optDict)
        let secondAsset = AVURLAsset(URL: NSURL(fileURLWithPath: secondVideo!), options: optDict)
        
        let composition = AVMutableComposition()
        do {
            let compositionTrack = composition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid)
            let firstTimeRange = CMTimeRange(start: kCMTimeZero, duration: firstAsset.duration)
            let secondTimeRange = CMTimeRange(start: kCMTimeZero, duration: secondAsset.duration)
            
            // 添加视频
            try compositionTrack.insertTimeRange(secondTimeRange, ofTrack: secondAsset.tracksWithMediaType(AVMediaTypeVideo).first!, atTime: kCMTimeZero)
            try compositionTrack.insertTimeRange(firstTimeRange, ofTrack: firstAsset.tracksWithMediaType(AVMediaTypeVideo).first!, atTime: kCMTimeZero)
            
            // 添加声音
            let audioTrack = composition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: kCMPersistentTrackID_Invalid)
            try audioTrack.insertTimeRange(secondTimeRange, ofTrack: secondAsset.tracksWithMediaType(AVMediaTypeAudio).first!, atTime: kCMTimeZero)
            try audioTrack.insertTimeRange(firstTimeRange, ofTrack: firstAsset.tracksWithMediaType(AVMediaTypeAudio).first!, atTime: kCMTimeZero)
            
            let cache = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).last
            let filePath = cache! + "/comp_sw.mp4"
            
            let exporterSession = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetHighestQuality)
            exporterSession?.outputFileType = AVFileTypeMPEG4
            exporterSession?.outputURL = NSURL(fileURLWithPath: filePath)
            exporterSession?.shouldOptimizeForNetworkUse = true
            exporterSession?.exportAsynchronouslyWithCompletionHandler({ () -> Void in
                switch exporterSession!.status {
                case .Unknown:
                    print("unknow")
                case .Cancelled:
                    print("cancelled")
                case .Failed:
                    print("failed")
                case .Waiting:
                    print("waiting")
                case .Exporting:
                    print("exporting")
                case .Completed:
                    print("completed")
                }
            })
        } catch {
            print("\(error)")
        }
    }

0x10 效果 (时间变化)

1.png
2.png
合并后.png

欢迎大家交流指正

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,898评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,401评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,058评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,539评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,382评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,319评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,706评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,370评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,664评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,715评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,476评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,326评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,730评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,003评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,275评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,683评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,877评论 2 335

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,952评论 4 60
  • 手阳明大肠经左右共40个穴位,昨天就全部说完了。 手阳明大肠经的主治 一、经络症:齿痛颈肿,口干喉痹,鼻塞流涕,鼻...
    锦似半夏阅读 3,263评论 3 20
  • by枫木溪水 留些黑夜给白天, 白天说他没这么阴险。 留...
    达瓦枫溪阅读 195评论 0 1
  • 告别的时刻,总是有点心酸。一段经历,一个故事,一个人,没有区别。 我将告别两年的周末时光,这两年来我花了500个小...
    茉莉大大阅读 185评论 0 0
  • 题目链接 Search a 2D Matrix Write an efficient algorithm that...
    哈比猪阅读 120评论 0 0