Save tracks from AudioEngine to file

Hi all,

I'm using AVAudioEngine to play multiple nodes at various times (like GarageBand for example).
So far I managed to play the various files at the right time using this code :

Code Block
DispatchQueue.global(qos: .background).async {
            AudioManager.instance.audioEngine.attach(AudioManager.instance.mixer)
            AudioManager.instance.audioEngine.connect(AudioManager.instance.mixer, to: AudioManager.instance.audioEngine.outputNode, format: nil)
          // !important - start the engine *before* setting up the player nodes
          try! AudioManager.instance.audioEngine.start()
          
          for audioFile in data {
            // Create and attach the audioPlayer node for this file
            let audioPlayer = AVAudioPlayerNode()
            AudioManager.instance.audioEngine.attach(audioPlayer)
            AudioManager.instance.nodes.append(audioPlayer)
            // Notice the output is the mixer in this case
            AudioManager.instance.audioEngine.connect(audioPlayer, to: AudioManager.instance.mixer, format: nil)
            let fileUrl = audioFile.audio.fileUrl
            if let file : AVAudioFile = try? AVAudioFile.init(forReading: fileUrl) {
                let time = audioFile.start > 0 ? AudioManager.instance.secondsToAVAudioTime(hostTime: mach_absolute_time(), time: Double(audioFile.start / CGFloat.secondsToPoints)) : nil
                audioPlayer.scheduleFile(file, at: time, completionHandler: nil)
                audioPlayer.play(at: time)
            }
          }
        }


Basically my data object contains struct that have a reference to an audio fileURL and the startPosition at which it should begin.

That works great.
now I would like to export all these tracks mixed into a single file and save it to the Document's directory of the user.

How can I achieve this?

Thanks for your help.
One approach is to install a tap on the output of the main mixer (https://developer.apple.com/documentation/avfoundation/avaudionode/1387122-installtap). This will provide you with a series of AVAudioPCMBuffers which you can write to a file of whatever format you chose with AVAudioFile.
Thanks @polyphonic, but from what I understood, I have to play the track in order for the tap to work right? I can render the mixed track in background. Is that correct ? thanks.
If you disconnect the mixer from the output node, your tap should be able to capture the data without playing any sound. You can also look into the manual rendering mode, which may speed things up if you don't need to hear the sound being captured:
Code Block
https://developer.apple.com/documentation/avfoundation/avaudioengine

(Scroll down to "Manually Rendering an Audio Engine".)
Thanks a lot, I'll look at it ;-)
Save tracks from AudioEngine to file
 
 
Q