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.

Accepted Reply

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.

  • Thanks. Indeed it is always AVAudioPCMBuffer as far as I have tried. I wander why they did not reflect this in the signature of the callback though.

Add a Comment

Replies

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.

  • Thanks. Indeed it is always AVAudioPCMBuffer as far as I have tried. I wander why they did not reflect this in the signature of the callback though.

Add a Comment