The Red Penguin

setPosition control


Friday 31 July 2020

We're going to do the final piece of work on the DJAudioPlayer class where we implement the set position control.

1. Go to DJAudioPlayer.cpp and the DJAudioPlayer::setPosition function. Type this:
void DJAudioPlayer::setPosition(double posInSecs)
{
transportSource.setPosition(posInSecs);
}

2. Let's hook this up to a slider. So if we go back to the MainComponent.h we can add this in private:
juce::Slider posSlider;

3. In MainComponent.cpp we add the code in the relevant places as follows:
addAndMakeVisible(posSlider);
posSlider.addListener(this);
double rowH = getHeight() / 6;
posSilder.setBounds(0, rowH * 4, getWidth(), rowH);
loadButton.setBounds(0, rowH * 5, getWidth(), rowH);

4. Now we've added this as a listener event we need to receive the values from the slider like this:
    if (slider == &posSlider)
{
player1.setPosition(slider->getValue());
}
}

5. We could have a problem in that we can only set the slider to the first 10 seconds. So to correct this we can use implement a function to deal with the relative position. In DJAudioPlayer.h in public: we add:
void setPositionRelative(double pos);

6. We then go to DJAudioPlayer.cpp and implement it by typing this:
void DJAudioPlayer::setPositionRelative(double pos)
{
if (pos < 0 || pos > 1.0)
{
DBG("DJAudioPlayer::setPositionRelative pos should be between 0 and 1");
}
else
{
double posInSecs = transportSource.getLengthInSeconds() * pos;
setPosition(posInSecs);
}
}

7. Then go to MainComponent.cpp to let it call setPositionRelative instead of setPosition:
if (slider == &posSlider)
{
player1.setPositionRelative(slider->getValue());
}

8. Finally we need to make sure the slider is in the range 0 to 1 so at the top of MC.cpp we add:
posSlider.setRange(0.0, 1.0);

Finally build and compile and everything is working as expected!