How to write AVAudioBuffer to a file?

If the audio buffer is AVAudioPCMBuffer, it is possible to write it into a file using AVAudioFile's writeFromBuffer:error: method.

How should plain AVAudioBuffer be handled?

In my specific case, I get this buffer from the callback of AVSpeechSynthesizer's writeUtterance:toBufferCallback:

In fact the documentation says:

// Use this method to receive audio buffers that can be used to store or further process synthesized speech.
// The dictionary provided by -[AVSpeechSynthesisVoice audioFileSettings] can be used to create an AVAudioFile.
- (void)writeUtterance:(AVSpeechUtterance *)utterance toBufferCallback:(AVSpeechSynthesizerBufferCallback)bufferCallback API_AVAILABLE(ios(13.0), watchos(6.0), tvos(13.0), macos(10.15)) ;

But I don't know how exactly AVAudioFile can be used if the buffer is not guaranteed to be an AVAudioPCMBuffer.

Answered by OOPer in 686829022

How should plain AVAudioBuffer be handled?

AVAudioBuffer is sort of an abstract super type of AVAudioPCMBuffer. You can check its type and cast it to AVAudioPCMBuffer.

And as far as I tried, writeUtterance:toBufferCallback: always uses AVAudioPCMBuffer as buffer. You may need to abandon further processing if it was not.

Accepted Answer

How should plain AVAudioBuffer be handled?

AVAudioBuffer is sort of an abstract super type of AVAudioPCMBuffer. You can check its type and cast it to AVAudioPCMBuffer.

And as far as I tried, writeUtterance:toBufferCallback: always uses AVAudioPCMBuffer as buffer. You may need to abandon further processing if it was not.

How to write AVAudioBuffer to a file?
 
 
Q