2

I recently have struggling to get AVMutableComposition working in my synthesizer app. I implemented a function like the one below without Audiokit and it worked perfectly fine. However, when I run the function below I only can here the first file in the files arrray in the outputed AKAudioFile. Is this a problem with how AKAudioFiles are copied or how AVMutableComposition works?

private func createCombinedRecordingFrom(_ files: [AKAudioFile], completion: @escaping (AKAudioFile?) -> ()) {
    let composition = AVMutableComposition()

    for file in files {
        let asset = file.avAsset

        let timeRange = CMTimeRange(start: kCMTimeZero, duration: asset.duration)
        let track = composition.addMutableTrack(withMediaType: .audio,
                                                preferredTrackID: kCMPersistentTrackID_Invalid)
        do {
            try track?.insertTimeRange(timeRange, of: asset.tracks[0], at: kCMTimeZero)
        } catch {
            print(error.localizedDescription)
            completion(nil)
        }
    }

    let assetExport = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A)!
    assetExport.audioTimePitchAlgorithm = .spectral
    assetExport.outputFileType = .m4a

    let temporaryURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString).appendingPathExtension("m4a")
    assetExport.outputURL = temporaryURL
    assetExport.exportAsynchronously() {
        do {
            let audioFile = try AKAudioFile(forReading: temporaryURL)
            completion(audioFile)
        } catch {
            print(error.localizedDescription)
            completion(nil)
        }
    }
}
Grant Emerson
  • 404
  • 1
  • 4
  • 13

0 Answers0