Can I occasionally create new AudioBuffers on audio thread?

Hello everyone!

I’m new to JUCE. I know that allocating memory on an audio thread is bad.
But consider my problem -
I have a recorder component. It’s getting called from getNextAudioBlock, it copies data rendered by a synth from input AudioBuffer (from AudioSourceChannelInfo) into the recorder’s AudioBuffer so that it’d be possible to export a .wav file from it later.
I don’t know for how long a user will be recording. I use a vector of AudioBuffers, when one of them is filled I create a new one. So my question is - how bad of a practice this is? After all, I’m allocating memory on the audio thread, not on every call of getNextAudioBlock of course, but every once in a while.

Thank you!

If you allocate memory in the audio thread, there’s always a risk that messes things up. You should do that only when absolutely necessary, for example to prevent a crash.

For recording for arbitrary length, it’s best to just write into a file on disk. Direct disk I/O in the audio thread is also “bad”, but Juce has the helper class AudioFormatWriter::ThreadedWriter to do that in a background thread.


There is also a great example for the above mentioned ThreadedWriter. JUCE: Tutorial: Processing audio input

This occasionally might mess you’re recording up in a sense that the audio thread might not have the time to do everything inside the real time boundaries. If you can life with the possibility that you might drop a few samples :wink:
Using the ThreadedWriter has a different kind of downside. If the background thread is not fast enough with emptying the queue, I think you’d be also dropping frames.

1 Like

Thank you!
AudioFormatWriter::ThreadedWriter worked like a charm.
Also, this example helped me a lot - AudioRecordingDemo.h.