Is it possible to split the recorded wav file into multiple wav files on iOS, given the duration of the splits?

StackOverflow https://stackoverflow.com/questions/21577693

  •  07-10-2022
  •  | 
  •  

Question

I want to extract a few clips from the recorded wav file. I am not finding much help online regarding this issue. I understand we can't split from compressed formats like mp3, but how do we do it with caf/wav files?

Was it helpful?

Solution

One approach you may consider would be to calculate and read the bytes from an audio file and write them to a new file. Because you are dealing with LPCM formats the calculations are relatively simple.

If for example you have a file of 16bit mono LPCM audio sampled at 44.1kHz that is one minute in duration, then you have a total of (60 secs x 44100Hz) 2,646,000 samples. Times 2 bytes per sample gives a total of 5,292,000 bytes. And if you want audio from 10sec to 30sec then you need to read the bytes from 882,000 to 2,646,000 and write them to a separate file.

There is a bit of code involved but it can be done using Audio File Services Class from the AudioToolbox framework.

Functions you'll need to use are AudioFileOpenURL, AudioFileCreateWithURL, AudioFileReadBytes, AudioFileWriteBytes, and AudioFileClose.

An algorithm would be something like this-

You first set up an AudioFileID which is an opaque type that gets passed in to the AudioFileCreateWithURL function. Then open the file you wish to splice up using AudioFileOpenURL.

Calculate the start and end bytes of what you want to copy.

Next, in a loop preferably, read in the bytes and write them to file. AudioFileReadBytes and AudioFileWriteBytes allow you to do this. Whats good is that you can read and write whatever size bytes you decide on each iteration of the loop.

When finished close the new file and original using AudioFileClose.

Then repeat for each file (audio extraction) to be written.

On an additional note you would split a compressed format by converting the compressed format to LPCM first.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top