[resolved] Slight code issue with the white noise generator tutorial


#1

I missed the block at the beginning of the tutorial that has a link to a downloadable zip with the full (working) source of the project. Whoops!


Hey y’all,
There’s a bug in the provided code in the white noise generator tutorial.

void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override
{
    for (int channel = 0; channel < bufferToFill.buffer->getNumChannels(); ++channel)
    {
        // Get a pointer to the start sample in the buffer for this audio output channel
        float* const buffer = bufferToFill.buffer->getWritePointer (channel, bufferToFill.startSample);
        
        // Fill the required number of samples with noise betweem -0.125 and +0.125
        for (int sample = 0; sample < bufferToFill.numSamples; ++sample)
            buffer[sample] = random.nextFloat() * 0.25f - 0.125f;
    }
}

xcode was complaining about random.nextFloat() with the error message:

Member reference base type ‘long ()’ is not a structure or union

Adding this line right before the for statement fixed the issue (and caused the application window to open and output white noise when ran in xcode).

Random random (0);

I’m very new to C++, so let me know if this doesn’t make sense.


#2

If you initialize random locally, it will always output the same data for each block. You can use it without initialisation in which case it will automatically create a random seed:

void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override
{
    Random random;
    for (int channel = 0; channel < bufferToFill.buffer->getNumChannels(); ++channel)
    [...]
}

Even better would be to declare random as class member:

void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override
{
    [...]
}
private:
    Random random;

#3

…which is exactly what the code in the tutorial has:

...
    void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override
    {
        for (int channel = 0; channel < bufferToFill.buffer->getNumChannels(); ++channel)
        {
            // Get a pointer to the start sample in the buffer for this audio output channel
            float* const buffer = bufferToFill.buffer->getWritePointer (channel, bufferToFill.startSample);
            
            // Fill the required number of samples with noise betweem -0.125 and +0.125
            for (int sample = 0; sample < bufferToFill.numSamples; ++sample)
                buffer[sample] = random.nextFloat() * 0.25f - 0.125f;
        }
    }

private:
    Random random;  ///<<<<<---- !!!
...

#4

Ah–missed the downloadable zip! I was building the code up in my own project, using the blocks provided in the body of the tutorial. I’ve amended the thread title to state this was resolved, and will update the first post with an indication, thanks!


#5

Thanks for the description–defining in the private section of the code makes sense now!