I’m new here, trying to understand the “Opening a file” part of the Tutorial: Build an audio player.
I really cannot figure out why are we creating a
auto newSource = std::make_unique<juce::AudioFormatReaderSource> (reader, true);
instead of just using the already existent member
std::unique_ptr<juce::AudioFormatReaderSource> readerSource;
and we pass the reader to readerSource, but two lines later … why the extra step ?
this is the code in the tutorial :
chooser->launchAsync (chooserFlags, [this] (const juce::FileChooser& fc) // [8]
{
auto file = fc.getResult();
if (file != juce::File{}) // [9]
{
auto* reader = formatManager.createReaderFor (file); // [10]
if (reader != nullptr)
{
auto newSource = std::make_unique<juce::AudioFormatReaderSource> (reader, true); // [11]
transportSource.setSource (newSource.get(), 0, nullptr, reader->sampleRate); // [12]
playButton.setEnabled (true); // [13]
readerSource.reset (newSource.release()); // [14]
}
}
});
the tutorial explains : We store the [AudioFormatReaderSource] object in a temporary std::unique_ptr object to avoid deleting a previously allocated [AudioFormatReaderSource] prematurely on subsequent commands to open a file.
But I cannot understand how this code is doing something like that if between that line and the releasing that unique_ptr the only thing happening is :
transportSource.setSource (newSource.get(), 0, nullptr, reader->sampleRate); // [12]
playButton.setEnabled (true);
is not the same just doing ?:
chooser->launchAsync (chooserFlags, [this] (const juce::FileChooser& fc) // [8]
{
auto file = fc.getResult();
if (file != juce::File{}) // [9]
{
auto* reader = formatManager.createReaderFor (file); // [10]
if (reader != nullptr)
{
//auto newSource = std::make_unique<juce::AudioFormatReaderSource>(reader, true); // [11]
readerSource.reset();
readerSource = std::make_unique<juce::AudioFormatReaderSource> (reader, true); // [11]
transportSource.setSource (readerSource.get(), 0, nullptr, reader->sampleRate); // [12]
playButton.setEnabled (true); // [13]
//readerSource.reset (newSource.release()); // [14]
}
}
});
This code throws when trying to load a file for the second time. But I don’t understand why.
The documentation says transportSource.setSource() does not delete the source and that it needs to be managed by the caller so it should not be a problem with the code above.
