AVAssetExportSession exporting a longer audio file

Hi,

I'm using an AVMutableComposition in order to add 0.1 seconds of sound from an .aac file to an .m4a file, then exporting that composition via AVAssetExportSession:

//after loadValuesAsynchronously tracks&duration for both silenceAsset and finalAsset
let sourceAudioTrack = finalAsset.tracks(withMediaType: .audio).first
let silenceAudioTrack = silenceAsset.tracks(withMediaType: .audio).first
let track = composition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid)
let startTime = CMTime(seconds: 0, preferredTimescale: 1)
let trackDuration = finalAsset.duration
let tRange = CMTimeRange(start: startTime, duration: trackDuration)

let trackMix = AVMutableAudioMixInputParameters(track: track)
trackMix.setVolume(1, at: startTime)

do {
    try track.insertTimeRange(tRange, of: sourceAudioTrack, at: startTime)

    let endRange = CMTimeRange(start: startTime, duration: CMTimeMakeWithSeconds(0.1, preferredTimescale: 100))

    try track.insertTimeRange(endRange, of: silenceAudioTrack, at: trackDuration)
} catch {}

let exporter = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A)

let audioMix = AVMutableAudioMix()
audioMix.inputParameters = [trackMix]
exporter.audioMix = audioMix
exporter.outputFileType = .m4a
exporter.outputURL = "whatever.m4a"

exporter.exportAsynchronously {
    guard exporter.status == .completed,
               let outputURL = exporter.outputURL else {
        completion(nil)
        return
    }

    completion(outputURL)
}

The file resulted from the export session doesn't always have the duration expected and reported by track.timeRange.end.seconds right after adding all the timeRanges.

In my specific case, I have the unadulterated m4a file with 1.87 seconds. I take it through this process once, I get a file with 1.97 seconds. I take this new file and do it again - track.timeRange reports a total duration of 2.07 seconds, which is correct, but the exported file has 2.136s. I do it again with the exported file, track.timeRange reports 2.236s, the exported file has 2.321s.

I've never encountered this issue before and I have been trimming/appending to audio files with this method for 2 years now. Is it a system bug? Am I missing something?

AVAssetExportSession exporting a longer audio file
 
 
Q