Mixing two Audio Files using AVComposition on IOS

给你一囗甜甜゛ 提交于 2019-12-03 09:09:58

I'm posting the code that I eventually got to work, in case anybody else is trying to do the same thing and would like some code samples (My problem above I suspect was that the audio files weren't being loaded correctly)

 [self showActivityIndicator]; // This code takes a while so show the user an activity Indicator
AVMutableComposition *composition = [AVMutableComposition composition];
NSArray* tracks = [NSArray arrayWithObjects:@"backingTrack", @"RobotR33", nil];
NSString* audioFileType = @"wav";

for (NSString* trackName in tracks) {
    AVURLAsset* audioAsset = [[AVURLAsset alloc]initWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:trackName ofType:audioFileType]]options:nil];

    AVMutableCompositionTrack* audioTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio
                                                                     preferredTrackID:kCMPersistentTrackID_Invalid];

    NSError* error;
    [audioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset.duration) ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio]objectAtIndex:0] atTime:kCMTimeZero error:&error];
    if (error)
    {
        NSLog(@"%@", [error localizedDescription]);
    }
}
AVAssetExportSession* _assetExport = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetAppleM4A];

NSString* mixedAudio = @"mixedAudio.m4a";

NSString *exportPath = [NSTemporaryDirectory() stringByAppendingString:mixedAudio];
NSURL *exportURL = [NSURL fileURLWithPath:exportPath];

if ([[NSFileManager defaultManager]fileExistsAtPath:exportPath]) {
    [[NSFileManager defaultManager]removeItemAtPath:exportPath error:nil];
}
_assetExport.outputFileType = AVFileTypeAppleM4A;
_assetExport.outputURL = exportURL;
_assetExport.shouldOptimizeForNetworkUse = YES;

[_assetExport exportAsynchronouslyWithCompletionHandler:^{
    [self hideActivityIndicator];
    NSLog(@"Completed Sucessfully");
}];

For Swift 3

    showActivityIndicator()  
    var composition = AVMutableComposition()
    var tracks: [Any] = ["backingTrack", "RobotR33"]
    var audioFileType: String = "wav"
    for trackName: String in tracks {
        var audioAsset = AVURLAsset(url: URL(fileURLWithPath: Bundle.main.path(forResource: trackName, ofType: audioFileType)), options: nil)
        var audioTrack: AVMutableCompositionTrack? = composition.addMutableTrack(withMediaType: AVMediaTypeAudio, preferredTrackID: kCMPersistentTrackID_Invalid)
        var error: Error?
        try? audioTrack?.insertTimeRange(CMTimeRangeMake(kCMTimeZero, audioAsset.duration), of: audioAsset.tracks(withMediaType: AVMediaTypeAudio)[0], atTime: kCMTimeZero)
        if error != nil {
            print("\(error?.localizedDescription)")
        }
    }
    var _assetExport = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A)
//  Converted with Swiftify v1.0.6355 - https://objectivec2swift.com/
var mixedAudio: String = "mixedAudio.m4a"
var exportPath: String = NSTemporaryDirectory() + (mixedAudio)
var exportURL = URL(fileURLWithPath: exportPath)
if FileManager.default.fileExists(atPath: exportPath) {
    try? FileManager.default.removeItem(atPath: exportPath)
}
assetExport.outputFileType = AVFileTypeAppleM4A
assetExport.outputURL = exportURL
assetExport.shouldOptimizeForNetworkUse = true
assetExport.exportAsynchronously(withCompletionHandler: {() -> Void in
    self.hideActivityIndicator()
    print("Completed Sucessfully")
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!