The Red Penguin

Refactor DJAudioPlayer to use app-scope formatManager


Wednesday 5 August 2020

1. At the moment we have AudioFormatManager in DJAudioPlayer.h. What we want to do is update DJAudioPlayer so that it takes an AudioFormatManager into its constructor, to force us to have to pass one to it.

We're going to change the type of this to reference (&), so that when we pass it in to the DJAudioPlayer, it will be able to store the same data, not make a copy of it.

That's very important when you are parsing objects into other objects, and expecting the second object to store that objective parsed in as a reference, then you must make sure that the data type that you specify as reference on both the function call and the variable itself. So we add the &

juce::AudioFormatManager& formatManager;

2. We need to change the constructor now so where it says DJAudioPlayer(); we now need to change it to:
DJAudioPlayer (juce::AudioFormatManager& _formatManager);

3. So now we update DJAudioPlayer.cpp and where it says DJAudioPlayer::DJAudioPlayer() change this to:
DJAudioPlayer::DJAudioPlayer(juce::AudioFormatManager& _formatManager) : formatManager(_formatManager)

Notice we have also created an initialisation list here too. So now it should have access to the format manager.

4. In DJAudioPlayer.cpp in DJAudioPlayer::prepareToPlay we're going to delete formatManager.registerBasicFormats(); as we're going to assume it's been initialised already and we don't need to call it again.

5. The next step is to check the MainComponent is calling this constructor correctly. We go to MainComponent.h and change code to this:
DJAudioPlayer player1{formatManager};
DeckGUI deckGUI1{&player1, formatManager, thumbCache};

DJAudioPlayer player2{formatManager};
DeckGUI deckGUI2{&player2, formatManager, thumbCache};

We have succeeded in refactoring so we have one global format manager.