How to apply gain correctly to the sampler?

Hello, everyone! As a Juce beginner I would like to ask you about one thing I’ve been trying to figure out for quite a bit of time, but unfortunately without any proper result.

Based on the tutorials about building Sampler on the YouTube (TheAudioProgrammer channel), I decided to add a gain to the sampler for myself.
Here are the parameter characteristics:
“GAIN”, “Gain”, juce::NormalisableRange { -40.0f, 0.2f, 0.1f }, 0.1f, “dB”.

in case 1: when I just get the gain parameter from AudioProcessorValueTreeState and apply it straightly to the given buffer in PluginProcessor.cpp in processBlock function, I get nothing in effect, here’s code:

void SamplerAudioProcessor::processBlock (juce::AudioBuffer& buffer, juce::MidiBuffer& midiMessages)

buffer.applyGain(juce::Decibels::decibelsToGain(getCurrentGain())); //without ramp, just to make it
mSampler.renderNextBlock(buffer, midiMessages, 0, buffer.getNumSamples());

in case 2: when I try to apply gain by accessing the buffer getAudioData() of the uploaded sound file to the sampler, as a result I get terrible sound explosion (apparently the sounds gets madly loud) and afterwards I don’t hear the sound at all:

void SamplerAudioProcessor::updateGain()
auto gain = mAPVTS.getRawParameterValue(“GAIN”)->load();
for (int i = 0; i < mSampler.getNumSounds(); ++i)
if (auto sound = dynamic_castjuce::SamplerSound*(mSampler.getSound(i).get()))
auto samplerBuffer = sound->getAudioData();
plus the call of this function in processBlock…

I guess that in case 2 my mistake is that I edit the data irrevocably, thus I don’t fully understand why the code from case 1 doesn’t work… But I might be totally off, due to probable lack of understanding.

Mainly I don’t know what is is the volume set by default once I upload the file to the sampler itself…

I would be sooooo happy, if someone could help me with any tip!
Thanks for reading and for your attention!

In your case 1, you are doing the calls in the wrong order, you should first call the renderNextBlock of the synth/sampler, and then apply the gain.

In your case 2, you seem to be causing an accumulating gain change on the audio buffers used by the sampler. I would avoid even trying to do something like that.

Oh thank you so much!! Now it works:)