How to append two audio files?

后端 未结 2 1198
半阙折子戏
半阙折子戏 2021-01-01 06:16

I want to append two audio files in iPhone. Please help me to do this.

2条回答
  •  粉色の甜心
    2021-01-01 06:28

    I got the solution; Following is the sample code to do it.

    AVMutableComposition* composition = [AVMutableComposition composition];
    AVURLAsset* audioAsset1 = [[AVURLAsset alloc]initWithURL:[NSURL fileURLWithPath:filePath1] options:nil];
    AVURLAsset* audioAsset2 = [[AVURLAsset alloc]initWithURL:[NSURL fileURLWithPath:filePath2] options:nil];
    
    AVMutableCompositionTrack *audioTrack1 = [composition addMutableTrackWithMediaType:AVMediaTypeAudio 
                                                                          preferredTrackID:kCMPersistentTrackID_Invalid];
    
    [audioTrack1 insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset1.duration)
                             ofTrack:[[audioAsset1 tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0]
                              atTime:kCMTimeZero
                               error:&error];
    [audioTrack1 insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset2.duration) 
                             ofTrack:[[audioAsset2 tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] 
                              atTime:audioAsset1.duration
                               error:&error];

    Finally, we have to export it as a single file using AVAssetExportSession.

    NOTE: It will work only for .m4a files

提交回复
热议问题