SoFunction
Updated on 2025-05-19

Complete code to implement audio and video merging in iOS

1. Audio merge (multi-segment audio stitching)

Put multiple audio files (such as.mp3.m4a) Merge into one audio file.

Code Example

// Merge audio files (support .mp3/.m4a and other formats)- (void)mergeAudioFiles:(NSArray<NSURL *> *)audioURLs completion:(void (^)(NSURL *outputURL, NSError *error))completion {
    // 1. Create AVMutableComposition object    AVMutableComposition *composition = [AVMutableComposition composition];
    
    // 2. Add audio track    AVMutableCompositionTrack *audioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
    
    // 3. Insert each audio file into the track    CMTime currentTime = kCMTimeZero;
    for (NSURL *url in audioURLs) {
        AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
        AVAssetTrack *assetTrack = [[asset tracksWithMediaType:AVMediaTypeAudio] firstObject];
        [audioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, )
                         ofTrack:assetTrack
                          atTime:currentTime
                           error:nil];
        currentTime = CMTimeAdd(currentTime, );
    }
    
    // 4. Export the merged audio    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetAppleM4A];
    NSString *outputPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"mergedAudio.m4a"];
     = [NSURL fileURLWithPath:outputPath];
     = AVFileTypeAppleM4A;
    
    [exportSession exportAsynchronouslyWithCompletionHandler:^{
        if ( == AVAssetExportSessionStatusCompleted) {
            NSLog(@"Audio merge successfully: %@", outputPath);
            if (completion) completion([NSURL fileURLWithPath:outputPath], nil);
        } else {
            NSError *error = ;
            NSLog(@"Audio merge failed: %@", );
            if (completion) completion(nil, error);
        }
    }];
}

How to use

// Example: Merge two audio filesNSArray<NSURL *> *audioURLs = @[
    [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"audio1" ofType:@"mp3"]],
    [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"audio2" ofType:@"mp3"]]
];

[self mergeAudioFiles:audioURLs completion:^(NSURL *outputURL, NSError *error) {
    if (outputURL) {
        NSLog(@"Merged audio path: %@", );
    }
}];

2. Video merge (multi-segment video)

Put multiple video files (such as.mp4) Merge it into one video file.

Code Example

// Merge video files (support .mp4 and other formats)- (void)mergeVideoFiles:(NSArray<NSURL *> *)videoURLs completion:(void (^)(NSURL *outputURL, NSError *error))completion {
    // 1. Create AVMutableComposition object    AVMutableComposition *composition = [AVMutableComposition composition];
    
    // 2. Add video tracks and audio tracks    AVMutableCompositionTrack *videoTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
    AVMutableCompositionTrack *audioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
    
    // 3. Insert each video file into the track    CMTime currentTime = kCMTimeZero;
    for (NSURL *url in videoURLs) {
        AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
        AVAssetTrack *videoAssetTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] firstObject];
        AVAssetTrack *audioAssetTrack = [[asset tracksWithMediaType:AVMediaTypeAudio] firstObject];
        
        [videoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, )
                         ofTrack:videoAssetTrack
                          atTime:currentTime
                           error:nil];
        [audioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, )
                         ofTrack:audioAssetTrack
                          atTime:currentTime
                           error:nil];
        currentTime = CMTimeAdd(currentTime, );
    }
    
    // 4. Export the merged video    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetHighestQuality];
    NSString *outputPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"mergedVideo.mp4"];
     = [NSURL fileURLWithPath:outputPath];
     = AVFileTypeMPEG4;
    
    [exportSession exportAsynchronouslyWithCompletionHandler:^{
        if ( == AVAssetExportSessionStatusCompleted) {
            NSLog(@"Video merge successfully: %@", outputPath);
            if (completion) completion([NSURL fileURLWithPath:outputPath], nil);
        } else {
            NSError *error = ;
            NSLog(@"Video merge failed: %@", );
            if (completion) completion(nil, error);
        }
    }];
}

How to use

// Example: Merge two video filesNSArray<NSURL *> *videoURLs = @[
    [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"video1" ofType:@"mp4"]],
    [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"video2" ofType:@"mp4"]]
];

[self mergeVideoFiles:videoURLs completion:^(NSURL *outputURL, NSError *error) {
    if (outputURL) {
        NSLog(@"Merged video path: %@", );
    }
}];

3. Audio and video merge (combining audio and video)

Merge separate audio files and video files into a media file containing audio and video.

Code Example

// Merge audio and video- (void)mergeAudio:(NSURL *)audioURL withVideo:(NSURL *)videoURL completion:(void (^)(NSURL *outputURL, NSError *error))completion {
    // 1. Create AVMutableComposition object    AVMutableComposition *composition = [AVMutableComposition composition];
    
    // 2. Add video track    AVMutableCompositionTrack *videoTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
    AVURLAsset *videoAsset = [AVURLAsset URLAssetWithURL:videoURL options:nil];
    AVAssetTrack *videoAssetTrack = [[videoAsset tracksWithMediaType:AVMediaTypeVideo] firstObject];
    [videoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, )
                     ofTrack:videoAssetTrack
                      atTime:kCMTimeZero
                       error:nil];
    
    // 3. Add audio track    AVMutableCompositionTrack *audioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
    AVURLAsset *audioAsset = [AVURLAsset URLAssetWithURL:audioURL options:nil];
    AVAssetTrack *audioAssetTrack = [[audioAsset tracksWithMediaType:AVMediaTypeAudio] firstObject];
    [audioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, )
                     ofTrack:audioAssetTrack
                      atTime:kCMTimeZero
                       error:nil];
    
    // 4. Export the merged audio and video    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetHighestQuality];
    NSString *outputPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"mergedMedia.mp4"];
     = [NSURL fileURLWithPath:outputPath];
     = AVFileTypeMPEG4;
    
    [exportSession exportAsynchronouslyWithCompletionHandler:^{
        if ( == AVAssetExportSessionStatusCompleted) {
            NSLog(@"Audio and video merge successfully: %@", outputPath);
            if (completion) completion([NSURL fileURLWithPath:outputPath], nil);
        } else {
            NSError *error = ;
            NSLog(@"Audio and video merge failed: %@", );
            if (completion) completion(nil, error);
        }
    }];
}

How to use

// Example: Merge an audio and a video fileNSURL *audioURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"backgroundMusic" ofType:@"mp3"]];
NSURL *videoURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"video" ofType:@"mp4"]];

[self mergeAudio:audioURL withVideo:videoURL completion:^(NSURL *outputURL, NSError *error) {
    if (outputURL) {
        NSLog(@"Merged audio and video path: %@", );
    }
}];

4. Things to note

  • Sampling rate and encoding format

    • When merging audio, make sure that the sampling rate (such as 44.1kHz) of all audio files are consistent, otherwise resampling is required first.
    • When merging videos, ensure that the resolution and frame rate of all videos are consistent, otherwise it needs to be adjusted to unified parameters.
  • Performance optimization

    • useAVAssetExportSessionofAVAssetExportPresetLowQualityorAVAssetExportPresetMediumQualityReduce the export quality to speed up processing.
    • When merging large files, it is recommended to process them in segments or use background threads.
  • Error handling

    • examineanderrorInformation to ensure the stability of the merge process.
  • Resource release

    • After the merge is complete, delete the temporary file to free up storage space.

5. Third-party tool recommendations

If more complex audio and video processing (such as cropping, filtering, transcoding), you can combine the following tools:

  • FFmpeg:passFFmpeg-iOSAchieve powerful audio and video processing functions.
  • GPUImage: Used for real-time video filtering and image processing.
  • Lame: Used for audio encoding (such as MP3).

Through the above solutions, you can efficiently realize the audio and video merging function on the iOS platform, suitable for short video stitching, music creation, podcast production and other scenarios.

This is the article about the complete code for the implementation of audio and video merging in iOS. For more related audio and video merging in iOS, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!