A Quick(ish) Way to Concatenate Audio in Swift
1 min readJan 30, 2018
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)
}
}
}