The Red Penguin

Implementing setGain and setSpeed


Friday 31 July 2020

1. In DJAudioPlayer.h we need to add in private:
juce::ResamplingAudioSource resampleSource{&transportSource, false, 2};


2. We need to hook this up into the audio life cycle. So we go to DJAudioPlayer.cpp and in DJAudioPlayer::prepareToPlay we add:
resampleSource.prepareToPlay(samplesPerBlockExpected, sampleRate);

3. In DJAudioPlayer::getNextAudioBlock we replace transportSource with resampleSource
resampleSource.getNextAudioBlock(bufferToFill); 

4. We need to releaseResources on the resampleSource as well:
resampleSource.releaseResources();

5. That completes the implementation and the next step is to hook that up to the sliders. So we go down to DJAudioPlayer::setGain and type
void DJAudioPlayer::setGain(double gain)
{
if (gain < 0 || gain > 1.0)
{
DBG("DJAudioPlayer::setGain gain should be between 0 and 1");
}
else
{
transportSource.setGain(gain);
}
}

We've put in a check her to make sure the gain stays between 0 and 1.

6. We can do something similar in setSpeed:
void DJAudioPlayer::setSpeed(double ratio)
{
if (ratio < 0 || ratio > 100.0)
{
DBG("DJAudioPlayer::setSpeed speed should be between 0 and 100");
}
else
{
resampleSource.setResamplingRatio(ratio);
}
}

7. We need to go back out to the MainComponent layer and send these numbers in through the sliders. So go to MainComponent.cpp and type
void MainComponent::sliderValueChanged(juce::Slider* slider)
{
if (slider == &volSlider)
{
player1.setGain(slider->getValue());
}
if (slider == &speedSlider)
{
player1.setSpeed(slider->getValue());
}
}

So let's build and compile that - can we control the speed and volume of the audio player? Yes!