AudioBuffer::makeCopyOf vs. copyFrom vs. operator=()

I was just reading this thread

realising that I’m using AudioBuffer::makeCopyOf in my processBlock :see_no_evil:

now what is the best approach if you want to copy the buffer from processBlock?

juce::AudioBuffer<float> myBuffer;

for (int channel = 0; channel < totalNumInputChannels ; channel++)
        myBuffer.copyFrom(channel, 0, buffer, channel, 0, buffer.getNumSamples());

or simply

juce::AudioBuffer<float> myBuffer
myBuffer = buffer;

And I’m also wondering, if you shall not use makeCopyOf on the audio thread, what is this function good for?


The copyFrom is the preferred.
Note that you need to take care of the length, since the buffer in processBlock is not guaranteed to be always the same length. So you need to store the actual number of samples.

I don’t trust using the AudioBuffer with avoidAllocation, but maybe that’s just me. AudioBuffer is sometimes too clever for my taste internally.

For usage when you are not on the audio thread :wink:

1 Like

Is that safe enough? In my case I’m only reading the magnitude of each channel in the buffer.

if (buffer.getNumSamples() < myBuffer.getNumSamples()) // possible!!
        myBuffer.clear(); // zero out if buffer is smaller than myBuffer

auto numSamplesToCopy = jmin(myBuffer.getNumSamples(), buffer.getNumSamples());

for (int channel = 0; channel < totalNumInputChannels; channel++)
    myBuffer.copyFrom(channel, 0, buffer, channel, 0, numSamplesToCopy);

Or should I better use

if (buffer.getNumSamples() != myBuffer.getNumSamples())
    myBuffer.setSize(buffer.getNumChannels(), buffer.getNumSamples(), false, true, false);

instead of clear() ?