Write a .wav file from buffer example

Is there a current example of how to simply write an AudioBuffer to a wave file?

Somehow I can’t find anything. Thanks.

That’s the code:

AudioBuffer<float> buffer;
WavAudioFormat format;
std::unique_ptr<AudioFormatWriter> writer;
writer.reset (format.createWriterFor (new FileOutputStream (file),
                                      48000.0,
                                      buffer.getNumChannels(),
                                      24,
                                      {},
                                      0));
if (writer != nullptr)
    writer->writeFromAudioSampleBuffer (buffer, 0, buffer.getNumSamples());

Hope that helps

1 Like

Thanks, but I’m getting errors…

  • Allocating an object of abstract class type ‘juce::OutputStream’
  • No member named ‘createWriter’ in ‘juce::WavAudioFormat’
  • Unknown type name ‘OutputFileStream’; did you mean ‘OutputStream’?

Should be FileOutputStream, and createWriteFor() :wink:

Sloppy me, shouldn’t write out of my head… :slight_smile: thanks, I’ll edit the code above

Thanks, gents.

I’m still a little stunned that I couldn’t find an example of writing a wav file anywhere on the forum or docs.

Here is some code, just a little more elaborate:

1 Like

Thanks, but your first example is exactly what I needed. I found quite a few streaming examples but I just needed to write an AudioBuffer. Thanks again.

Trying to write wav file, what am I doing wrong?

AudioBuffer<float> buffer(1, singleChannelAudio.size());

auto ptr = buffer.getWritePointer(0);

for (int f = 0; f < singleChannelAudio.size(); ++f)
    ptr[f] = float(singleChannelAudio[f]);

WavAudioFormat format;
std::unique_ptr<AudioFormatWriter> writer;
writer.reset(format.createWriterFor(new FileOutputStream(path), sampleRate, 1, bitDepth, {}, 0));

if (writer == nullptr)
    return false;

writer->writeFromAudioSampleBuffer(buffer, 0, buffer.getNumSamples());    

return true;

this gives error:

That code works for me (with the obvious additions to allow it to compile). There’s probably some problem with the file path you are using. Maybe trying to write to a directory that doesn’t exist or the directory doesn’t have write permissions.

1 Like

file wasn’t created due to bad file name

In the example, the active writer thread is using inputChannelData, which is a float** and not a buffer.
activeWriter.load()->write (inputChannelData, numSamples);
(JUCE/AudioRecordingDemo.h at 90e8da0cfb54ac593cdbed74c3d0c9b09bad3a9f · juce-framework/JUCE · GitHub)

How can I use a buffer to write directly using the thread like so, so that the modified buffer is written to the wav file via the stream:
activeWriter.load()->write (buffer, numSamples);

Thanks

You can always get the raw float pointers from a buffer using getArrayOfReadPointers():

activeWriter.load()->write (buffer.getArrayOfReadPointers(), buffer.getNumSamples());

HTH