This can be done quite easily using AVMutableComposionTrack insertTimeRange:ofTrack:atTime:error . The code is somewhat long, but it is really the same as 4 steps:
// Create a new audio track we can append to AVMutableComposition* composition = [AVMutableComposition composition]; AVMutableCompositionTrack* appendedAudioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid]; // Grab the two audio tracks that need to be appended AVURLAsset* originalAsset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:originalAudioPath] options:nil]; AVURLAsset* newAsset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:newAudioPath] options:nil]; NSError* error = nil; // Grab the first audio track and insert it into our appendedAudioTrack AVAssetTrack *originalTrack = [originalAsset tracksWithMediaType:AVMediaTypeAudio]; CMTimeRange timeRange = CMTimeRangeMake(kCMTimeZero, originalAsset.duration); [appendedAudioTrack insertTimeRange:timeRange ofTrack:[originalTrack objectAtIndex:0] atTime:kCMTimeZero error:&error]; if (error) { // do something return; } // Grab the second audio track and insert it at the end of the first one AVAssetTrack *newTrack = [newAsset tracksWithMediaType:AVMediaTypeAudio]; timeRange = CMTimeRangeMake(kCMTimeZero, newAsset.duration); [appendedAudioTrack insertTimeRange:timeRange ofTrack:[newTrack objectAtIndex:0] atTime:originalAsset.duration error:&error]; if (error) { // do something return; } // Create a new audio file using the appendedAudioTrack AVAssetExportSession* exportSession = [AVAssetExportSession exportSessionWithAsset:composition presetName:AVAssetExportPresetAppleM4A]; if (!exportSession) { // do something return; } NSString* appendedAudioPath= @""; // make sure to fill this value in exportSession.outputURL = [NSURL fileURLWithPath:appendedAudioPath]; exportSession.outputFileType = AVFileTypeAppleM4A; [exportSession exportAsynchronouslyWithCompletionHandler:^{ // exported successfully? switch (exportSession.status) { case AVAssetExportSessionStatusFailed: break; case AVAssetExportSessionStatusCompleted: // you should now have the appended audio file break; case AVAssetExportSessionStatusWaiting: break; default: break; } NSError* error = nil; }];
memmons
source share