Wednesday, 28 August 2013

Unable to generate new audio file from AVComposition

Unable to generate new audio file from AVComposition

I am trying to mix two audio files in the main bundle and save the final
audio, but this code gives errors.
if I change the output file type to, _assetExport.outputFileType =
@"com.apple.quicktime-movie"; and the output file name to,
audioJoined.mov. then it works. But I don't want it to be a video file. I
want the output as an audio.
NSString *documentDirectory =
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,
YES) objectAtIndex:0];
NSURL *audioURL = [[NSBundle mainBundle] URLForResource:@"sample2"
withExtension:@"mp3"];
NSURL *audioURL2 = [[NSBundle mainBundle] URLForResource:@"sample"
withExtension:@"mp3"];
AVURLAsset* audioAsset = [[AVURLAsset alloc]initWithURL:audioURL
options:nil];
AVURLAsset* audioAsset2 = [[AVURLAsset alloc]initWithURL:audioURL2
options:nil];
AVMutableComposition* mixComposition = [AVMutableComposition
composition];
AVMutableCompositionTrack *compositionCommentaryTrack =
[mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio
preferredTrackID:kCMPersistentTrackID_Invalid];
[compositionCommentaryTrack
insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset.duration)
ofTrack:[[audioAsset
tracksWithMediaType:AVMediaTypeAudio]
objectAtIndex:0]
atTime:kCMTimeZero error:nil];
AVMutableCompositionTrack *compositionAudioTrack = [mixComposition
addMutableTrackWithMediaType:AVMediaTypeAudio
preferredTrackID:kCMPersistentTrackID_Invalid];
[compositionAudioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero,
audioAsset2.duration)
ofTrack:[[audioAsset2
tracksWithMediaType:AVMediaTypeAudio]
objectAtIndex:0]
atTime:kCMTimeZero error:nil];
AVAssetExportSession* _assetExport = [[AVAssetExportSession alloc]
initWithAsset:mixComposition
presetName:AVAssetExportPresetPassthrough];
NSString *soundFilePath = [documentDirectory
stringByAppendingPathComponent: @"audioJoined.caf"];
NSLog(@"soundFilePath:%@", soundFilePath);
NSURL *savetUrl = [NSURL fileURLWithPath:soundFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:soundFilePath])
{
[[NSFileManager defaultManager] removeItemAtPath:soundFilePath
error:nil];
}
NSLog (@"created exporter. supportedFileTypes: %@",
_assetExport.supportedFileTypes);
_assetExport.outputFileType = AVFileTypeCoreAudioFormat;
_assetExport.outputURL = savetUrl;
_assetExport.shouldOptimizeForNetworkUse = YES;
[_assetExport exportAsynchronouslyWithCompletionHandler:^{
switch (_assetExport.status)
{
case AVAssetExportSessionStatusCompleted:
NSLog(@"Completed exporting!");
break;
case AVAssetExportSessionStatusFailed:
NSLog(@"Failed:%@", _assetExport.error.description);
break;
case AVAssetExportSessionStatusCancelled:
NSLog(@"Canceled:%@", _assetExport.error);
break;
default:
break;
}
}];

No comments:

Post a Comment