In my app I combine several .m4a
audio files. For combining audio files I use below code.
CMTime nextClipStartTime = kCMTimeZero;
AVMutableComposition *composition = [[AVMutableComposition alloc] init];
AVMutableCompositionTrack *compositionAudioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
for(NSString * str in filesNamesArray)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:str];
NSURL *url = [[NSURL alloc] initFileURLWithPath:path];
AVAsset *avAsset = [[AVURLAsset alloc] initWithURL:url options:nil];
NSArray *tracks = [avAsset tracksWithMediaType:AVMediaTypeAudio];
if ([tracks count] == 0)
{
NSLog(@"Tracks = %lu",(unsigned long)[tracks count]);
return;
}
NSLog(@"%@",avAsset);
CMTimeRange timeRangeInAsset = CMTimeRangeMake(kCMTimeZero, [avAsset duration]);
AVAssetTrack *clipAudioTrack = [[avAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
ok = [compositionAudioTrack insertTimeRange:timeRangeInAsset ofTrack:clipAudioTrack atTime:nextClipStartTime error:&error];
if (!ok) {
NSLog(@"Current Video Track Error: %@",error);
}
nextClipStartTime = CMTimeAdd(nextClipStartTime, timeRangeInAsset.duration);
}
Sometimes 'tracksWithMediaType' returns empty array. Why is this happening and any help would be greatly appreciated.
When you create AVAsset with:
asset must have loaded its tracks before ready for use: