Decode OGG from memory to memory


I would like to decode OGG data (NKS preview files) directly from memory into memory, so users can listen to a short preview if the NKS preview-files are installed from within my own browser.

The idea is that if a preset is selected (just selected, not double clicked or anything), the code would load the entire OGG file into memory (it’s maximum of six seconds long) and decode it into memory, where it can then be mixed into the output of the plugin for instant preview (similar how it works in the Komplete Kontrol browsers).

I’ve looked at the OggVorbisAudioFormat class etc. but it seems a bit convoluted. Is there a demo somewhere, or can somebody with more experience in that field post a short code-snipped?


1 Like

Is there some particular reason you want the file decoded in memory too? Because you could just load the source file into memory and create an AudioFormatReader out of that memory block with AudioFormatManager. Or you could even just read and decode the file directly from disk, but you might want to do some buffered reading for that, though…(JUCE has the BufferingAudioReader for that.)

Both, the AudioFormatReader and AudioFormatWriter support using an InputStream/OutputStream, so you can use a MemoryOutputStream to write to:

MemoryBlock memory;
OggVorbisAudioFormat format;
    MemoryOutputStream* output = new MemoryOutputStream (memory, false);
    std::unique_ptr writer (format.createWriterFor (output, samplerate, ...));
    if (writer)
        writer->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());
        delete (output);
std::unique_ptr reader (format.createReaderFor (new MemoryInputStream (memory, false), true));
// ...
1 Like

@daniel Thanks, this should get me going.

@Xenakios Yes, I wanted to read from memory, so I can pre-cache the previous and next previews in memory myself and then trigger the decoding once the cursor moves.

In case someone else wants to do something similar:

    // Load entire OGG-file into memory-block
	MemoryBlock		inMemory;

	File ("test.ogg").loadFileAsData (inMemory);

    // Create an OGG audio-format reader
	OggVorbisAudioFormat	format;

	std::unique_ptr<AudioFormatReader> reader (format.createReaderFor (new MemoryInputStream (inMemory, false), true));

    // Decode entire OGG-file into a float audio buffer
    AudioBuffer<float>    outBuffer (2, (int)reader->lengthInSamples);

    reader->read (&outBuffer, 0, (int)reader->lengthInSamples, 0, true, true);

The outBuffer now contains the complete decoded OGG-file in stereo (for mono-files, the left channel is automatically duplicated into the right).

Thanks again for pointing me in the right direction.