Write AAC files in a way that they are readable even in a crash

I'm building an audio recording app. For our users it's important that recordings never get lost - even if the app crashes, users would like to have the partial recording.

We encode recordings in AAC or ALAC and store them in an m4a file using AVAudioFile. However, in case the app crashes, those m4a files are invalid - the MOOV atom is missing.

Are there recording settings that change the m4a file so that it is always playable, even if the recording is interrupted half-way?

I'm not at all an expert in audio codecs, but from what I understand, it is possible to write the MOOV atom at the beginning of the audio file instead of the end. This could solve this. But of course, I'd prefer an actual expert to tell me what a good solution is, and how to configure this in AVAudioFile.

Have you tried using AVAssetWriter to write the file, using its movieFragmentInterval property?

Thanks, I didn’t know about AVAssetWriter. I‘ll try it out. On a first glance, movieFragmentInterval looks like it’s only relevant for QuickTime, not MPEG. However, shouldOptimizeForNetworkUse should do the trick - that should put the moov atom at the beginning of the container.

I‘ll report back once I tried it.

Edit: accidentally posted this from my private apple Id but I‘m the OP

I can confirm that shouldOptimizeForNetworkUse puts the moov atom at the beginning of the container. I verified this by opening an m4a file with an AVAssetReader and passing its content to an AVAssetWriter using AVAssetReaderInput and AVAssetWriterInput. This works like a charm.

However, when writing audio to the AVAssetWriterInput while I record, I need to convert the AVAudioPCMBuffer that I get from my tap on my audio input to a CMSampleBuffer that AVAssetWriterInput.append(sampleBuffer:) expects.

How do I do that? There are some answers on Google and StackOverflow on how to do it the other way around, but truth be told they don't seem particularly trustworthy.

Write AAC files in a way that they are readable even in a crash
 
 
Q