A Quick(ish) Way to Concatenate Audio in Swift

It feels like joining two audio files in iOS should be one or two lines of code.

It isn’t.

My latest attempt uses AVMutableCompositions to join the audio segments and AVAssetExportSession to export it. I wrote a little extension to make it a little cleaner

The basic implementation looks like this:

let composition = AVMutableComposition()
let compositionAudioTrack = composition.addMutableTrack(withMediaType: AVMediaTypeAudio, preferredTrackID: kCMPersistentTrackID_Invalid)

compositionAudioTrack.append(url: audioUrl1)
compositionAudioTrack.append(url: audioUrl2)

if let assetExport = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetPassthrough) {
assetExport.outputFileType = AVFileTypeWAVE
assetExport.outputURL = recordingUrl
assetExport.exportAsynchronously(completionHandler: {})
}

And this is what the extension on AVMutableCompositionTrack looks like:

extension AVMutableCompositionTrack {
func append(url: URL) {
let newAsset = AVURLAsset(url: url)
let range = CMTimeRangeMake(kCMTimeZero, newAsset.duration)
let end = timeRange.end
print(end)
if let track = newAsset.tracks(withMediaType: AVMediaTypeAudio).first {
try! insertTimeRange(range, of: track, at: end)
}

}
}

--

--

Music App Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store