I want to export a movie with AVAssetWriter
and can\'t figure out how to include video and audio tracks in sync. Exporting only video works fine, but when I add aud
It seams that assetWriterAudioInput ignores sample buffer time for audio writing. Do this way.
1) Write video track.
2) When done, mark it finished i.e. [videoWriterInput markAsFinished];
3) do [assetWriter startSessionAtSourceTime:timeRangeStart];
3) instantiate audio reader and start writing audio.
-(void)mergeAudioVideo
{
NSString *videoOutputPath=[_documentsDirectory stringByAppendingPathComponent:@"dummy_video.mp4"];
NSString *outputFilePath = [_documentsDirectory stringByAppendingPathComponent:@"final_video.mp4"];
if ([[NSFileManager defaultManager]fileExistsAtPath:outputFilePath])
[[NSFileManager defaultManager]removeItemAtPath:outputFilePath error:nil];
NSURL *outputFileUrl = [NSURL fileURLWithPath:outputFilePath];
NSString *filePath = [_documentsDirectory stringByAppendingPathComponent:@"newFile.m4a"];
AVMutableComposition* mixComposition = [AVMutableComposition composition];
NSURL *audio_inputFileUrl = [NSURL fileURLWithPath:filePath];
NSURL *video_inputFileUrl = [NSURL fileURLWithPath:videoOutputPath];
CMTime nextClipStartTime = kCMTimeZero;
AVURLAsset* videoAsset = [[AVURLAsset alloc]initWithURL:video_inputFileUrl options:nil];
CMTimeRange video_timeRange = CMTimeRangeMake(kCMTimeZero,videoAsset.duration);
AVMutableCompositionTrack *a_compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
[a_compositionVideoTrack insertTimeRange:video_timeRange ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:nextClipStartTime error:nil];
AVURLAsset* audioAsset = [[AVURLAsset alloc]initWithURL:audio_inputFileUrl options:nil];
CMTimeRange audio_timeRange = CMTimeRangeMake(kCMTimeZero, audioAsset.duration);
AVMutableCompositionTrack *b_compositionAudioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
[b_compositionAudioTrack insertTimeRange:audio_timeRange ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:nextClipStartTime error:nil];
AVAssetExportSession* _assetExport = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetMediumQuality];
_assetExport.outputFileType = @"com.apple.quicktime-movie";
_assetExport.outputURL = outputFileUrl;
[_assetExport exportAsynchronouslyWithCompletionHandler:
^(void ) {
if (_assetExport.status == AVAssetExportSessionStatusCompleted) {
//Write Code Here to Continue
}
else {
//Write Fail Code here
}
}
];
}
You can use this code to merge audio and video.