AudioFormatReaderSource get()

In the AudioThumbnailTutorial_04.h line 307 there’s a AudioFormatReaderSource (variablename: newSource) created.

In the next line newSource is transformed (perhaps the wrong word?) to a PositionableAudioSource using a .get() method. How does this work? I don’t understand what’s happening there. What’s the purpose of get() and why can I not find it in the Juce reference?
I found there’s a std::get but I’m not sure I get the relation and functionality here.

Also, since newSource, reader and file goes out of scope when launchAsync is finished where’s the actual audiosample data stored/referenced for the remainder of the session?

chooser->launchAsync (chooserFlags, [this] (const FileChooser& fc)
            auto file = fc.getResult();

            if (file != File{})
                auto* reader = formatManager.createReaderFor (file);

                if (reader != nullptr)
                    auto newSource = std::make_unique<juce::AudioFormatReaderSource> (reader, true);
                    transportSource.setSource (newSource.get(), 0, nullptr, reader->sampleRate);
                    playButton.setEnabled (true);
                    thumbnailComp.setFile (file);
                    readerSource.reset (newSource.release());

The get function there is a member of std::unique_ptr. It returns a raw pointer to the object managed by the unique_ptr.

A pointer to an AudioFormatReaderSource can implicitly convert to a pointer to a PositionableAudioSource. AudioFormatReaderSource is derived from PositionableAudioSource. This means that AudioFormatReaderSource “is a” PositionableAudioSource - it’s just a more specialised kind of PositionableAudioSource. All the operations that you can do on a PositionableAudioSource can also be done on a AudioFormatReaderSource, which is why it makes sense to allow conversions between these pointer types. This implicit conversion between pointers to subtypes/supertypes is a built-in behaviour of C++. If you’ve not encountered it before, it might be worth reading about inheritance in a C++ textbook.

The final line in that scope (readerSource.reset (newSource.release())) transfers ownership of the object originally managed by newSource to readerSource. This audio source can be accessed via readerSource from that point onwards.

1 Like

Great, thanks for the explanation. Yes, inheritance is familiar. I actually learned C++ in the nineties but haven’t used it since so there’s a lot of news. I’m beginning to understand (some of) the new std::stuff now.