前面的文章我介紹了如何將多張圖片合成視頻,這篇文章將繼續(xù)介紹如何將同時(shí)錄制的音頻合成到視頻文件中(音頻的錄制就不做介紹了,使用AVAudioRecorder就可錄制音頻)。
下面直接貼代碼介紹吧
+ (void)mergeVideo:(NSString *)videoPath andAudio:(NSString *)audioPath withCompletion:(ZYSExportVideoCompletion)completion {
// 視頻和音頻源文件
NSURL *videoURL = [NSURL fileURLWithPath:videoPath];
NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
// 最終合成后文件的輸出路徑
NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
NSString *outputPath = [docPath stringByAppendingPathComponent:@"ScreenRecord.mp4"];
NSFileManager *fm = [NSFileManager defaultManager];
if ([fm fileExistsAtPath:outputPath]) {
if (![fm removeItemAtPath:outputPath error:nil]) {
NSLog(@"remove old output file failed.");
}
}
NSURL *outputURL = [NSURL fileURLWithPath:outputPath];
// 時(shí)間起點(diǎn)
CMTime startTime = kCMTimeZero;
// 創(chuàng)建音視頻組合操作類
AVMutableComposition *composition = [AVMutableComposition composition];
/// 視頻采集
AVURLAsset *videoAsset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
// 獲取視頻時(shí)間范圍
CMTimeRange videoTimeRange = CMTimeRangeMake(kCMTimeZero, videoAsset.duration);
// 創(chuàng)建視頻通道
AVMutableCompositionTrack *videoTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
// 創(chuàng)建視頻采集通道
AVAssetTrack *videoAssetTrack = [videoAsset tracksWithMediaType:AVMediaTypeVideo].firstObject;
// 將采集的視頻數(shù)據(jù)加入到可變軌道中
[videoTrack insertTimeRange:videoTimeRange ofTrack:videoAssetTrack atTime:startTime error:nil];
/// 音頻采集
AVURLAsset *audioAsset = [[AVURLAsset alloc] initWithURL:audioURL options:nil];
// 音頻時(shí)間范圍
CMTimeRange audioTimeRange = CMTimeRangeMake(kCMTimeZero, audioAsset.duration);
// 創(chuàng)建音頻通道
AVMutableCompositionTrack *audioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
// 獲取音頻采集通道
AVAssetTrack *audioAssetTrack = [audioAsset tracksWithMediaType:AVMediaTypeAudio].firstObject;
// 將采集的音頻數(shù)據(jù)添加到可變軌道中
[audioTrack insertTimeRange:audioTimeRange ofTrack:audioAssetTrack atTime:startTime error:nil];
// 創(chuàng)建一個(gè)視頻輸出
AVAssetExportSession *assetExport = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetMediumQuality];
// 視頻輸出類型
assetExport.outputFileType = AVFileTypeMPEG4;
// 視頻輸出地址
assetExport.outputURL = outputURL;
// 是否優(yōu)化視頻
assetExport.shouldOptimizeForNetworkUse = YES;
// 導(dǎo)出視頻
[assetExport exportAsynchronouslyWithCompletionHandler:^{
// 刪除原視頻、音頻文件
if ([fm fileExistsAtPath:videoPath]) {
if (![fm removeItemAtPath:videoPath error:nil]) {
NSLog(@"remove video.mp4 failed.");
}
}
if ([fm fileExistsAtPath:audioPath]) {
if (![fm removeItemAtPath:audioPath error:nil]) {
NSLog(@"remove audio.wav failed.");
}
}
if (completion) {
completion(outputPath);
}
}];
}