The Red Penguin

Add a file chooser


Thursday 30 July 2020

We're going to work on the audio playback code and make it a little bit more interactive so that the user can choose which audio file they want to play.

1. We're going to put the code in a function.

Go to MainComponent.cpp and MainComponent::prepareToPlay and remove this code:
    juce::URL audioURL{ "file:///b:/tracks/aon_inspired.mp3"};

auto* reader = formatManager.createReaderFor(audioURL.createInputStream(false));
if (reader != nullptr) // good file!
{
std::unique_ptr newSource(new juce::AudioFormatReaderSource(reader, true));
transportSource.setSource(newSource.get(), 0, nullptr, reader->sampleRate);
readerSource.reset(newSource.release());
transportSource.start();
}

2. Create a new function in MainComponent.h called loadURL(). So under juce::AudioTransportSource we type:
void loadURL(juce::URL audioURL);

3. We need to go to MainComponent.cpp and add the implementation of this function now. So at the bottom of the file we can add this:
    auto* reader = formatManager.createReaderFor(audioURL.createInputStream(false));
if (reader != nullptr) // good file!
{
std::unique_ptr newSource(new juce::AudioFormatReaderSource(reader, true));
transportSource.setSource(newSource.get(), 0, nullptr, reader->sampleRate);
readerSource.reset(newSource.release());
transportSource.start();
}

which is most of the code from point 1. We don't need to set the URL any more as that comes in the function.

4. We now need to trigger this code. We need to add a button that can call this code with a file chooser.

We go back to MainComponent.h and in private: add
juce::TextButton loadButton{ "LOAD" };

5. Go back to the constructor and add a button to the app. So we add these two lines in the appropriate place in MainComponent::MainComponent() in MainComponent.cpp:
addAndMakeVisible(loadButton);

loadButton.addListener(this);

6. Then go to the listener code in MainComponent::buttonClicked and add
if (button == &loadButton)
{
juce::FileChooser chooser{"select file"};
if (chooser.browseForFileToOpen())
{
loadURL(juce::URL{chooser.getResult()});
}
}

7. In resized() we need to set the setBounds
loadButton.setBounds(0, rowH * 3, getWidth(), rowH);

And now it all works!