我有一个应用程序,我需要将音频文件合并到 AVCapture 会话录制的视频中,以便可以听到录制电影的音频和合并的音频。
我能够使用 avcomposition 将音频合并到视频中,并且效果很好。但问题是无法听到原始音频文件。这是我的代码。
NSString *resourceAudioName = [NSString stringWithFormat:@"%@_audio",getTitle];
NSURL *audio_inputFileUrl = [[NSBundle mainBundle] URLForResource:resourceAudioName withExtension:@"mp3"];
NSString * video_inputFilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
video_inputFilePath = [video_inputFilePath stringByAppendingPathComponent:@"movie1.mp4"];
self.outputFilePath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/OutPutMovie-%@.mp4",[NSDate date]]];
NSURL * outputFileUrl = [NSURL fileURLWithPath:self.outputFilePath];
if (audio_inputFileUrl) {
AVMutableComposition* mixComposition = [AVMutableComposition composition];
NSURL * video_inputFileUrl = [NSURL fileURLWithPath:video_inputFilePath];
CMTime nextClipStartTime = kCMTimeZero;
AVURLAsset * videoAsset = [[AVURLAsset alloc]initWithURL:video_inputFileUrl options:nil];
NSArray * videoAssetTracks2 = [videoAsset tracksWithMediaType:AVMediaTypeVideo];
AVAssetTrack * videoAssetTrack2 = ([videoAssetTracks2 count] > 0 ? [videoAssetTracks2 objectAtIndex:0] : nil);
CMTimeRange video_timeRange = CMTimeRangeMake(kCMTimeZero,videoAsset.duration);
AVMutableCompositionTrack * a_compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
[a_compositionVideoTrack insertTimeRange:video_timeRange ofTrack:videoAssetTrack2 atTime:nextClipStartTime error:nil];
AVURLAsset * audioAsset = [[AVURLAsset alloc]initWithURL:audio_inputFileUrl options:nil];
NSArray * videoAssetTracks = [audioAsset tracksWithMediaType:AVMediaTypeAudio];
AVAssetTrack * videoAssetTrack = ([videoAssetTracks count] > 0 ? [videoAssetTracks objectAtIndex:0] : nil);
CMTimeRange audio_timeRange = CMTimeRangeMake(kCMTimeZero, audioAsset.duration);
AVMutableCompositionTrack * b_compositionAudioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
[b_compositionAudioTrack insertTimeRange:audio_timeRange ofTrack:videoAssetTrack atTime:nextClipStartTime error:nil];
AVAssetExportSession * _assetExport = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetHighestQuality];
_assetExport.outputFileType = @"com.apple.quicktime-movie";
_assetExport.outputURL = outputFileUrl;
[_assetExport exportAsynchronouslyWithCompletionHandler:
^(void ) {
if (AVAssetExportSessionStatusCompleted == _assetExport.status) {
[videoAsset release];
[audioAsset release];
[_assetExport release];
[self performSelectorOnMainThread:@selector(moveNextView) withObject:nil waitUntilDone:YES];
}
}
];