iOS音視頻合成

前言

最近有個(gè)音頻與視頻急灭,音頻與音頻合成的需求帽借,正好做個(gè)記錄珠增,其實(shí)主要是用到了AVFoundation中的AVMutableCompositionAVAssetExportSession這兩個(gè)類。廢話不多話砍艾,直接上代碼

音頻與視頻合成

#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];
        
        /** 設(shè)置輸出路徑 */
        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 - 調(diào)節(jié)合成的音量
+ (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;
}

/** 創(chuàng)建文件夾 */
+ (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];
    // 創(chuàng)建目錄
    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];
        
        /** 得到對(duì)應(yīng)軌道中的音頻聲音信息,并更改 */
        AVMutableAudioMixInputParameters *originalAudioParameters = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:originalAudio];
        [originalAudioParameters setVolume:originalAudioVolume atTime:kCMTimeZero];
        
        AVMutableAudioMixInputParameters *bgAudioParameters = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:bgAudio];
        [originalAudioParameters setVolume:bgAudioVolume atTime:kCMTimeZero];
        
        /** 賦給對(duì)應(yīng)的類 */
        AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
        audioMix.inputParameters = @[originalAudioParameters,bgAudioParameters];
        
        AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset:compostion presetName:AVAssetExportPresetAppleM4A];
        
        /** 設(shè)置輸出路徑 */
        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;
}


/** 創(chuàng)建文件夾 */
+ (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];
    // 創(chuàng)建目錄
    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];
        }
        
        /** 剪輯(設(shè)置導(dǎo)出的時(shí)間段) */
        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;
        
        /** 合成后的回調(diào) */
        [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;
                }
                
            });
            
            
        }];
    });
    
    
    
}

總結(jié)

以上就是個(gè)人總結(jié)的幾個(gè)處理音視頻的方法。以上方法我已封裝成一個(gè)工具類蜓谋,有需要請(qǐng)?jiān)?a target="_blank" rel="nofollow">這里下載梦皮。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市桃焕,隨后出現(xiàn)的幾起案子剑肯,更是在濱河造成了極大的恐慌,老刑警劉巖观堂,帶你破解...
    沈念sama閱讀 222,627評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件让网,死亡現(xiàn)場(chǎng)離奇詭異呀忧,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)溃睹,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,180評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén)而账,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人丸凭,你說(shuō)我怎么就攤上這事福扬。” “怎么了惜犀?”我有些...
    開(kāi)封第一講書(shū)人閱讀 169,346評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵铛碑,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我虽界,道長(zhǎng)汽烦,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 60,097評(píng)論 1 300
  • 正文 為了忘掉前任莉御,我火速辦了婚禮撇吞,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘礁叔。我一直安慰自己牍颈,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,100評(píng)論 6 398
  • 文/花漫 我一把揭開(kāi)白布琅关。 她就那樣靜靜地躺著煮岁,像睡著了一般。 火紅的嫁衣襯著肌膚如雪涣易。 梳的紋絲不亂的頭發(fā)上画机,一...
    開(kāi)封第一講書(shū)人閱讀 52,696評(píng)論 1 312
  • 那天,我揣著相機(jī)與錄音新症,去河邊找鬼步氏。 笑死,一個(gè)胖子當(dāng)著我的面吹牛徒爹,可吹牛的內(nèi)容都是我干的荚醒。 我是一名探鬼主播,決...
    沈念sama閱讀 41,165評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼隆嗅,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼腌且!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起榛瓮,我...
    開(kāi)封第一講書(shū)人閱讀 40,108評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤铺董,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體精续,經(jīng)...
    沈念sama閱讀 46,646評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡坝锰,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,709評(píng)論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了重付。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片顷级。...
    茶點(diǎn)故事閱讀 40,861評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖确垫,靈堂內(nèi)的尸體忽然破棺而出弓颈,到底是詐尸還是另有隱情,我是刑警寧澤删掀,帶...
    沈念sama閱讀 36,527評(píng)論 5 351
  • 正文 年R本政府宣布翔冀,位于F島的核電站,受9級(jí)特大地震影響披泪,放射性物質(zhì)發(fā)生泄漏纤子。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,196評(píng)論 3 336
  • 文/蒙蒙 一款票、第九天 我趴在偏房一處隱蔽的房頂上張望控硼。 院中可真熱鬧,春花似錦艾少、人聲如沸卡乾。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,698評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)幔妨。三九已至,卻和暖如春潮瓶,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背钙姊。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,804評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工毯辅, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人煞额。 一個(gè)月前我還...
    沈念sama閱讀 49,287評(píng)論 3 379
  • 正文 我出身青樓思恐,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親膊毁。 傳聞我的和親對(duì)象是個(gè)殘疾皇子胀莹,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,860評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容