0

I have multiple audios files(more than 3). By using the AVAudioEngine and AVAudioMixerNode I am playing the all audio tracks into a single track. I want to save the mixed audio in the document directory. Give suggestions to mix the multiple audios files and save in a document directory.

Thank you

Ajay
  • 185
  • 3
  • 18

1 Answers1

0

Try this:

func mergeAudioFiles(files: [URL], completion: @escaping (_ succeeded: Bool)->()) {
let composition = AVMutableComposition()
guard let compositionAudioTrack:AVMutableCompositionTrack = composition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: kCMPersistentTrackID_Invalid) else {
    completion(false)
    return
}

for fileUrl in files {
    let  asset = AVURLAsset(url: fileUrl, options: nil)
    let assetTrack = asset.tracks(withMediaType: AVMediaType.audio)[0]
    do {
        try compositionAudioTrack.insertTimeRange(assetTrack.timeRange, of: assetTrack, at: compositionAudioTrack.timeRange.duration)

    } catch {}
}

guard let exporter = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A) else {
    completion(false)
    return
}
exporter.outputFileType = AVFileType.m4a
exporter.outputURL =  URL(string: "AudioPathInDocumentsDirectory")
exporter.timeRange = compositionAudioTrack.timeRange

exporter.exportAsynchronously() {
    switch exporter.status {
    case .unknown,.waiting, .exporting:
        print("Exported Waiting")
    case .completed:
        print("Exported Complete")
        completion(true)
    case .failed:
        print("Exported Failed")
        completion(false)
    case .cancelled:
        print("Exported Cancelled")
    }
}
}
  • Hi Naser, Thank you for the reply. I used the above function in my code but it is not working. After this step, it is not going further guard let exporter = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A) else { completion(false) return } My audio files are .wav files. and those are in my Xcode – Ajay Oct 16 '18 at 04:53