'AVAssetExportSession is exporting audio with bad time range

I'm trying to trim an audio file, using the following snippet:

        let asset = AVURLAsset(url: sourceURL, options: [AVURLAssetPreferPreciseDurationAndTimingKey: true])

        guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A) else {
            throw AVUtilsError.assetExportSessionCreationFailure
        }

        let startCMTime = CMTime(seconds: startTime, preferredTimescale: CMTimeScale.max)
        let durationCMTime = CMTime(seconds: duration, preferredTimescale: CMTimeScale.max)
        let timeRange = CMTimeRange(start: startCMTime, duration: durationCMTime)

        exportSession.timeRange = timeRange
        exportSession.outputURL = outputFileURL
        exportSession.outputFileType = .m4a

        exportSession.exportAsynchronously {
            completion(exportSession.error)
        }

It's working correctly with almost all files, but with a minority of files, (e.g. this one: https://traffic.libsyn.com/secure/forcedn/theoakwynpodcast/The_Oakwyn_Podcast_ep102__V1.mp3) the times are misaligned with the trimming start/end points that I put visually in AVPlayer.

Am I missing something or is this a short-coming of AVFoundation?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source