How to concatenate 2 or 3 audio files in iOS?

后端 未结 7 1549
不知归路
不知归路 2020-12-08 12:19

I am newcomer in Objective-C and have experience only 5 months in iPhone development.

What I need:
I need to concatenate 2 or more

7条回答
  •  伪装坚强ぢ
    2020-12-08 12:34

    Code below can be used to merge audio files.

    Input files: Ids of the files to be supplied in array audioIds. Eg. audio1.mp3, audio2.mp3 … audioN.mp3 to be available in documents folder Output file: combined.m4a

         - (BOOL) combineVoices {
    
           NSError *error = nil;
           BOOL ok = NO;
    
    
             NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,    NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0]; 
    
    
           CMTime nextClipStartTime = kCMTimeZero;
            //Create AVMutableComposition Object.This object will hold our multiple AVMutableCompositionTrack.
            AVMutableComposition *composition = [[AVMutableComposition alloc] init];
    
         AVMutableCompositionTrack *compositionAudioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
    
         for (int i = 0; i< [self.audioIds count]; i++) {
            int key = [[self.audioIds objectAtIndex:i] intValue];
            NSString *audioFileName = [NSString stringWithFormat:@"audio%d", key];
    
            //Build the filename with path
            NSString *soundOne = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3", audioFileName]];
            //NSLog(@"voice file - %@",soundOne);
    
            NSURL *url = [NSURL fileURLWithPath:soundOne];    
            AVAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil];
            NSArray *tracks = [avAsset tracksWithMediaType:AVMediaTypeAudio];
            if ([tracks count] == 0) 
                return NO;
            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);
        }
    
        // create the export session
        // no need for a retain here, the session will be retained by the
        // completion handler since it is referenced there
        AVAssetExportSession *exportSession = [AVAssetExportSession
                                               exportSessionWithAsset:composition
                                               presetName:AVAssetExportPresetAppleM4A];
        if (nil == exportSession) return NO;
    
        NSString *soundOneNew = [documentsDirectory stringByAppendingPathComponent:@"combined.m4a"];
        //NSLog(@"Output file path - %@",soundOneNew);
    
        // configure export session  output with all our parameters
        exportSession.outputURL = [NSURL fileURLWithPath:soundOneNew]; // output path
        exportSession.outputFileType = AVFileTypeAppleM4A; // output file type
    
        // perform the export
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
    
            if (AVAssetExportSessionStatusCompleted == exportSession.status) {
                NSLog(@"AVAssetExportSessionStatusCompleted");
            } else if (AVAssetExportSessionStatusFailed == exportSession.status) {
                // a failure may happen because of an event out of your control
                // for example, an interruption like a phone call comming in
                // make sure and handle this case appropriately
                NSLog(@"AVAssetExportSessionStatusFailed");
            } else {
                NSLog(@"Export Session Status: %d", exportSession.status);
            }
        }];
    
        return YES;
    }
    

提交回复
热议问题