iOS音视频合成

前言

最近有个音频与视频,音频与音频合成的需求,正好做个记录,其实主要是用到了AVFoundation中的AVMutableCompositionAVAssetExportSession这两个类。废话不多话,直接上代码

音频与视频合成

#pragma mark - 音频与视频的合并
+ (void)mixVideoAndAudioWithVieoPath:(NSURL *)videoPath
                           audioPath:(NSURL *)audioPath
                      needVideoVoice:(BOOL)needVideoVoice
                         videoVolume:(CGFloat)videoVolume
                         audioVolume:(CGFloat)audioVolume
                      outPutFileName:(NSString *)fileName
                     complitionBlock:(CompletionBlock)completionBlock
{
    if (videoPath == nil) {
        return;
    }
    if (audioPath == nil) {
        return;
    }
    if (videoVolume > 1.0) {
        videoVolume = 1.0f;
    }
    if (videoVolume < 0.0) {
        videoVolume = 0.0f;
    }
    if (audioVolume > 1.0) {
        audioVolume = 1.0f;
    }
    if (audioVolume < 0.0) {
        audioVolume = 0.0f;
    }
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        AVAsset *asset      = [AVAsset assetWithURL:videoPath];
        AVAsset *audioAsset = [AVAsset assetWithURL:audioPath];
        
        CMTime duration = asset.duration;
        CMTimeRange video_timeRange = CMTimeRangeMake(kCMTimeZero, duration);
        
        AVAssetTrack *videoAssetTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
        AVAssetTrack *audioAssetTrack = [[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
        
        AVMutableComposition *composition = [[AVMutableComposition alloc]init];
        
        /** 视频素材加入视频轨道 */
        AVMutableCompositionTrack *videoCompositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
        [videoCompositionTrack insertTimeRange:video_timeRange ofTrack:videoAssetTrack atTime:kCMTimeZero error:nil];
        
        /** 音频素材加入音频轨道 */
        AVMutableCompositionTrack *audioCompositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
        [audioCompositionTrack insertTimeRange:video_timeRange ofTrack:audioAssetTrack atTime:kCMTimeZero error:nil];
        
        /** 是否加入视频原声 */
        AVMutableCompositionTrack *originalAudioCompositionTrack = nil;
        if (needVideoVoice) {
            AVAssetTrack *originalAudioAssetTrack = [[asset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
            originalAudioCompositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
            [originalAudioCompositionTrack insertTimeRange:video_timeRange ofTrack:originalAudioAssetTrack atTime:kCMTimeZero error:nil];
        }
        
        AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetMediumQuality];
        
        /** 设置输出路径 */
        NSURL *outputPath = [self exporterPathWithFileName:fileName];
        exporter.outputURL = outputPath;
        exporter.outputFileType = AVFileTypeQuickTimeMovie;
        exporter.shouldOptimizeForNetworkUse = YES;
        
        /** 音量控制 */
        exporter.audioMix = [self buildAudioMixWithVideoTrack:originalAudioCompositionTrack
                                                  VideoVolume:videoVolume
                                                   audioTrack:audioCompositionTrack
                                                  audioVolume:audioVolume
                                                       atTime:kCMTimeZero];
        
        [exporter exportAsynchronouslyWithCompletionHandler:^{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                switch ([exporter status]) {
                        
                    case AVAssetExportSessionStatusFailed: {
                        NSLog(@"合成失败:%@",[[exporter error] description]);
                        completionBlock(NO,outputPath);
                    }
                        break;
                        
                    case AVAssetExportSessionStatusCancelled: {
                        completionBlock(NO,outputPath);
                    }
                        break;
                        
                    case AVAssetExportSessionStatusCompleted: {
                        completionBlock(YES,outputPath);
                    }
                        break;
                        
                    default: {
                        completionBlock(NO,outputPath);
                    }
                        break;
                }
            });
            
            
        }];
        
    });
    
    
}

#pragma mark - 调节合成的音量
+ (AVAudioMix *)buildAudioMixWithVideoTrack:(AVCompositionTrack *)videoTrack
                                VideoVolume:(float)videoVolume
                                 audioTrack:(AVCompositionTrack *)audioTrack
                                audioVolume:(float)audioVolume
                                     atTime:(CMTime)volumeRange
{
    
    AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
    
    AVMutableAudioMixInputParameters *videoParameters = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:videoTrack];
    [videoParameters setVolume:videoVolume atTime:volumeRange];
    
    AVMutableAudioMixInputParameters *audioParameters = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:audioTrack];
    [audioParameters setVolume:audioVolume atTime:volumeRange];
    
    audioMix.inputParameters = @[videoParameters,audioParameters];
    
    return audioMix;
}

#pragma mark - 视频输出路径
+ (NSURL *)exporterPathWithFileName:(NSString *)outPutfileName
{
    NSString *fileName = [NSString stringWithFormat:@"%@.mp4",outPutfileName];
    
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSString *directoryName = @"editVideo";
    
    BOOL createDir = [self createDirWihtName:directoryName];
    
    if (createDir) {
        NSString *directory = [cachePath stringByAppendingPathComponent:directoryName];
        NSString *outputFilePath = [directory stringByAppendingPathComponent:fileName];
        
        if([[NSFileManager defaultManager] fileExistsAtPath:outputFilePath]) {
            
            [[NSFileManager defaultManager] removeItemAtPath:outputFilePath error:nil];
        }
        
        return [NSURL fileURLWithPath:outputFilePath];
    }
    
    return nil;
}

/** 创建文件夹 */
+ (BOOL)createDirWihtName:(NSString *)name
{
    if (!name) {
        return NO;
    }
    
    NSString      *cachePath    = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSFileManager *fileManager  = [NSFileManager defaultManager];
    NSString      *directory    = [cachePath stringByAppendingPathComponent:name];
    // 创建目录
    BOOL res = [fileManager createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:nil];
    
    return res;
}

音频与音频的合成

#pragma mark - 音频与音频的合并
+ (void)mixOriginalAudio:(NSURL *)originalAudioPath
     originalAudioVolume:(float)originalAudioVolume
             bgAudioPath:(NSURL *)bgAudioPath
           bgAudioVolume:(float)bgAudioVolume
          outPutFileName:(NSString *)fileName
         completionBlock:(CompletionBlock)completionBlock
{
    if (originalAudioPath == nil) {
        return;
    }
    if (bgAudioPath == nil) {
        return;
    }
    if (originalAudioVolume > 1.0) {
        originalAudioVolume = 1.0f;
    }
    if (originalAudioVolume < 0) {
        originalAudioVolume = 0.0f;
    }
    if (bgAudioVolume > 1.0) {
        bgAudioVolume = 1.0f;
    }
    if (bgAudioVolume < 0) {
        bgAudioVolume = 0.0f;
    }
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        AVURLAsset *originalAudioAsset = [AVURLAsset assetWithURL:originalAudioPath];
        AVURLAsset *bgAudioAsset       = [AVURLAsset assetWithURL:bgAudioPath];
        
        AVMutableComposition *compostion   = [AVMutableComposition composition];
        
        AVMutableCompositionTrack *originalAudio = [compostion addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:0];
        [originalAudio insertTimeRange:CMTimeRangeMake(kCMTimeZero, originalAudioAsset.duration) ofTrack:[originalAudioAsset tracksWithMediaType:AVMediaTypeAudio].firstObject atTime:kCMTimeZero error:nil];
        
        AVMutableCompositionTrack *bgAudio = [compostion addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:0];
        [bgAudio insertTimeRange:CMTimeRangeMake(kCMTimeZero, bgAudioAsset.duration) ofTrack:[bgAudioAsset tracksWithMediaType:AVMediaTypeAudio].firstObject atTime:kCMTimeZero error:nil];
        
        /** 得到对应轨道中的音频声音信息,并更改 */
        AVMutableAudioMixInputParameters *originalAudioParameters = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:originalAudio];
        [originalAudioParameters setVolume:originalAudioVolume atTime:kCMTimeZero];
        
        AVMutableAudioMixInputParameters *bgAudioParameters = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:bgAudio];
        [originalAudioParameters setVolume:bgAudioVolume atTime:kCMTimeZero];
        
        /** 赋给对应的类 */
        AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
        audioMix.inputParameters = @[originalAudioParameters,bgAudioParameters];
        
        AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset:compostion presetName:AVAssetExportPresetAppleM4A];
        
        /** 设置输出路径 */
        NSURL *outputPath = [self exporterAudioPathWithFileName:fileName];
        
        session.audioMix       = audioMix;
        session.outputURL      = outputPath;
        session.outputFileType = AVFileTypeAppleM4A;
        session.shouldOptimizeForNetworkUse = YES;
        
        [session exportAsynchronouslyWithCompletionHandler:^{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                switch ([session status]) {
                        
                    case AVAssetExportSessionStatusFailed: {
                        NSLog(@"合成失败:%@",[[session error] description]);
                        completionBlock(NO,outputPath);
                    }
                        break;
                        
                    case AVAssetExportSessionStatusCancelled: {
                        completionBlock(NO,outputPath);
                    }
                        break;
                        
                    case AVAssetExportSessionStatusCompleted: {
                        completionBlock(YES,outputPath);
                        
                    }
                        break;
                        
                    default: {
                        completionBlock(NO,outputPath);
                    }
                        break;
                }
                
            });
            
            
        }];
        
    });
    
    
    
}

#pragma mark - 音频输出路径
+ (NSURL *)exporterAudioPathWithFileName:(NSString *)outPutfileName
{
    NSString *fileName = [NSString stringWithFormat:@"%@.m4a",outPutfileName];
    
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSString *directoryName = @"editAudio";
    
    BOOL createDir = [self createDirWihtName:directoryName];
    
    if (createDir) {
        NSString *directory = [cachePath stringByAppendingPathComponent:directoryName];
        NSString *outputFilePath = [directory stringByAppendingPathComponent:fileName];
        
        if([[NSFileManager defaultManager] fileExistsAtPath:outputFilePath]) {
            
            [[NSFileManager defaultManager] removeItemAtPath:outputFilePath error:nil];
        }
        
        return [NSURL fileURLWithPath:outputFilePath];
    }
    
    return nil;
}


/** 创建文件夹 */
+ (BOOL)createDirWihtName:(NSString *)name
{
    if (!name) {
        return NO;
    }
    
    NSString      *cachePath    = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSFileManager *fileManager  = [NSFileManager defaultManager];
    NSString      *directory    = [cachePath stringByAppendingPathComponent:name];
    // 创建目录
    BOOL res = [fileManager createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:nil];
    
    return res;
}

音视频的剪辑

#pragma mark - 剪辑音视频
+ (void)cutMediaWithMediaType:(LYZMediaType)mediaType
                    mediaPath:(NSURL *)mediaPath
                    startTime:(CGFloat)startTime
                      endTime:(CGFloat)endTime
               outPutFileName:(NSString *)fileName
              complitionBlock:(CompletionBlock)completionBlock
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        AVAsset *asset = [AVAsset assetWithURL:mediaPath];
        
        AVAssetExportSession *exporter;
        
        if (mediaType == LYZMediaTypeAudio) {
            
            exporter = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetAppleM4A];
            
        } else if (mediaType == LYZMediaTypeVideo) {
            
            exporter = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetPassthrough];
        }
        
        /** 剪辑(设置导出的时间段) */
        CMTime start = CMTimeMakeWithSeconds(startTime, asset.duration.timescale);
        CMTime duration = CMTimeMakeWithSeconds(endTime - startTime,asset.duration.timescale);
        exporter.timeRange = CMTimeRangeMake(start, duration);
        
        NSURL *outputPath;
        
        if (mediaType == LYZMediaTypeAudio) {
            
            exporter.outputFileType = AVFileTypeAppleM4A;
            outputPath = [self exporterAudioPathWithFileName:fileName];
            exporter.outputURL = [self exporterAudioPathWithFileName:fileName];
            
        } else if (mediaType == LYZMediaTypeVideo) {
            
            exporter.outputFileType = AVFileTypeAppleM4V;
            outputPath = [self exporterPathWithFileName:fileName];
            exporter.outputURL = [self exporterPathWithFileName:fileName];
        }
        
        exporter.shouldOptimizeForNetworkUse = YES;
        
        /** 合成后的回调 */
        [exporter exportAsynchronouslyWithCompletionHandler:^{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                switch ([exporter status]) {
                        
                    case AVAssetExportSessionStatusFailed: {
                        NSLog(@"合成失败:%@",[[exporter error] description]);
                        completionBlock(NO,outputPath);
                    }
                        break;
                        
                    case AVAssetExportSessionStatusCancelled: {
                        completionBlock(NO,outputPath);
                    }
                        break;
                        
                    case AVAssetExportSessionStatusCompleted: {
                        completionBlock(YES,outputPath);
                    }
                        break;
                        
                    default: {
                        completionBlock(NO,outputPath);
                    }
                        break;
                }
                
            });
            
            
        }];
    });
    
    
    
}

总结

以上就是个人总结的几个处理音视频的方法。以上方法我已封装成一个工具类,有需要请在这里下载。

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

推荐阅读更多精彩内容