Artem Garmash Software developer, hardware enthusiast, mountain bike rider, musichead
Posts with the tag AVFoundation:

Trimming Audio Files and Adding Silence with AVFoundation in Swift

Originally posted in Akvelon Blog

While working on one of the apps, we faced the need to trim the recorded audio files. We were working with 32-bit float WAV files, and we had the following requirements:

  • the output file should have the exact same format as the input file;
  • no processing should be applied to the audio data, audio samples should be copied as-is;
  • there should be an ability to add silence to the output file.

My first guess was to use AVAssetExportSession, but it has limited options for exporting the audio, and it’s not possible to be sure what it does with the audio under the hood. A no-go.

Secondly, I took a look at the requirements again. “Audio samples should be copied as-is”. That was exactly what we needed - to open the input file for reading, the output one for writing, calculate the range of audio samples to copy, and perform the actual copying. Fortunately, it was completely possible with AVAudioFile - it can be read into AVAudioPCMBuffer and written from one’s contents.