juce::Span utilities for juce::AudioBuffer

It would be really nice if juce::AudioBuffer had some methods to get a juce::Span to represent a channel of audio, rather than just channel pointers as pointer arithmetic is discouraged in modern C++.

E.g. it would be really nice to be able to do

void processBlock(juce::AudioBuffer<float> buffer)
{
    for (const juce::Span channel : buffer)
    {
        for (float& sample : channel)
            sample *= 0.5f;
    }

    // or at least

    for (auto c = 0; c < buffer.getNumChannels(); ++c)
    {
        const juce::Span channel = buffer.getChannel(c);

        for (float& sample : channel)
            sample *= 0.5f;
    }
}

This would work nicely with juce::enumerate too when the channel or sample index is required.

+1 from me. Until something like this lands, a tiny free function gets you most of the way:

template <typename T>
juce::Span<T> getChannelSpan (juce::AudioBuffer<T>& buffer, int channel)
{
    return { buffer.getWritePointer (channel), (size_t) buffer.getNumSamples() };
}

void processBlock (juce::AudioBuffer<float>& buffer, juce::MidiBuffer&) override
{
    for (int ch = 0; ch < buffer.getNumChannels(); ++ch)
        for (auto& sample : getChannelSpan (buffer, ch))
            sample *= 0.5f;
}

On C++20 you can return a std::span<T> the same way. A const overload that uses getReadPointer is also worth adding.

One thing to watch: getWritePointer marks the buffer as “not clear”, so for read-only access use the const version. That way you keep the hasBeenCleared() optimisation. Also, as a side note, the example signature takes the buffer by reference, as you’d want in a real processBlock.

1 Like

Didn’t know about that optimisation, thanks!

A separate method for getting a read pointer is definitely a good idea - perhaps buffer.getChannelForReading() and buffer.getChannelForWriting().