Search code examples
iphoneiosobjective-cavaudiorecorder

Mixing two CAF file together


I have a problem here, in mixing of two CAF file.

First CAF File -> Fetching via a given url from server side

Second CAF File -> Recording with AVAudioRecorder

Fetch File Size - 10 sec

Recording File Size - 7 sec

How to mix these two given audio files in a single file, Please give me some sample code for same. Also format must be in CAF only.


Solution

  • An AVMutableComposition in the AVFoundation framework can do this; you do something like

    AVMutableComposition *comp = [AVMutableComposition new];
    AVMutableCompositionTrack *compTrack1 = [comp addMutableTrackWithMediaType:AVMediaTypeAudio 
        preferredTrackId:kCMPersistentTrackID_Invalid];
    AVMutableCompositionTrack *compTrack2 = [comp addMutableTrackWithMediaType:AVMediaTypeAudio 
        preferredTrackId:kCMPersistentTrackID_Invalid];
    
    AVAssetTrack *srcTrack1 = UseAVAssetToGetTrackfromFirstFile();
    AVAssetTrack *srcTrack2 = UseAVAssetToGetTrackfromSecondFile();
    
    NSError *error = nil;
    
        [compTrack1 insertTimeRange:CMTimeRangeMake(kCMTimeZero, kCMTimePositiveInfinity)
                                ofTrack:srcTrack1  
                                 atTime:kCMTimeZero error:&error];
    
        CheckForError(error);
    
        [compTrack2 insertTimeRange:CMTimeRangeMake(kCMTimeZero, kCMTimePositiveInfinity)
                                ofTrack:srcTrack2  
                                 atTime:kCMTimeZero error:&error];
    
        CheckForError(error);
    
    // emit mix from the composition here with a reader or whatever.
    

    You cans set relative levels with the composition too. If you needed to do anything more fancy than just levels and pan, though, you'd have to create an AudioUnit graph.