Is leaving OutputStream local OK?

Hi, I want to stream out a wav file, is OK if I leave OutStream as a local variable, I’m not sure if it’s needed while the writer is around?:

FileOutputStream *outputStream = new FileOutputStream(outputFile);
audioWriter = wavAudioFormat.createWriterFor(outputStream, currentSampleRate, numChannels, 16, "", 0);

audioWriter is a class member that streams out the file successfully later, then I delete it via the ScopedPointer mechanism.

The writer owns the stream:

    delete output;

Alternatively, you can check the repo:

Thanks for the quick reply. The local variable goes out of scope though, doesn’t it? So I can’t rely on the memory still being correct. I really don’t know what’s best.

Let’s take a look at your code:

    FileOutputStream* outputStream = new FileOutputStream (outputFile);
    audioWriter = wavAudioFormat.createWriterFor (outputStream, currentSampleRate, numChannels, 16, "", 0);

With outputStream being a pointer, the variable itself may disappear when it goes out of scope, but the memory it was pointing to does not. Seeing that the AudioFormatWriter owns the pointer, meaning it occupies itself with managing the memory the stream pointer is pointing to, you still have a way to access the stream (assuming the writer being created is valid!) - and the writer instance will clean the stream’s memory up when the writer is deleted.

This means we can simplify your code to a single line:

audioWriter = wavAudioFormat.createWriterFor (new FileOutputStream (outputFile), currentSampleRate, numChannels, 16, "", 0);
1 Like

Of course, silly me. Thanks for clearing the fog. :slight_smile:

Happy to help.

Just a quick FYI - the forum supports code formatting where you can wrap code up between a pair of triple-backticks. Helps with visually delimiting actual text and code… :slight_smile:

I’m using Chrome on Windows10. I’ve notice I can’t always get the formatting to work with pasted code, using the buttons on the editor. I did try several times. By ‘backtick’ I presume you mean the top- left key on the UK keyboard - it worked but not with the editor buttons. But I had to put the backticks on a new line for it to display properly.

I’m not sure about UK keyboard layouts, but you’re right that the triple backtick (also known as the grave accent) has to be on its own line.

It’s like Markdown and even Slack comments.

Just a little nitpicking:
Continuing to read the docs for WavAudioFormat::createWriterFor()

If no AudioFormatWriter can be created by this method, the stream will NOT be deleted, so that the caller can re-use it to try to open a different format, etc

If you take user supplied arguments, it could easily happen, but usually I would also think this is safe.

1 Like