As the other how-tos of this serie, this is also a side-effect of the project I’ve been working recently.

Libsndfile is a very popular library for reading and writing lossless audio files written by Erik de Castro Lopo. We use it in Clam and I’ve use it in other small applications.

This time I wanted to use the C++ wrapper (sndfile.hh header) added recently and, since I couldn’t find an example of use, well, time to post mine here.

I like a lot better the C++ api than the C one. See also the C sndfile API documentation.

#include <sndfile.hh>
#include <iostream>
#include <cmath>
int main()
{
	const int format=SF_FORMAT_WAV | SF_FORMAT_PCM_16;
//	const int format=SF_FORMAT_WAV | SF_FORMAT_FLOAT;
	const int channels=1;
	const int sampleRate=48000;
	const char* outfilename="foo.wav";

	SndfileHandle outfile(outfilename, SFM_WRITE, format, channels, sampleRate);
	if (not outfile) return -1;

	// prepare a 3 seconds buffer and write it
	const int size = sampleRate*3;
	float sample[size];
	float current=0.;
	for (int i=0; i<size; i++) sample[i]=sin(float(i)/size*M_PI*1500);
	outfile.write(&sample[0], size);
	return 0;
}

You’ll find a complete reference on the available formats on the sndfile API doc. But this are typical subformats of the Wav format. As in the example above, put them after the SF_FORMAT_WAV | portion:

Signed 16, 24, 32 bit data:

SF_FORMAT_PCM_16
SF_FORMAT_PCM_24
SF_FORMAT_PCM_32

Float 32, 64 bit data:

SF_FORMAT_FLOAT
SF_FORMAT_DOUBLE

2 Responses to “How to write wav files in C++ (using libsndfile)”

  1. Carl-Erik Says:

    Thanks for posting this! There is really not much info for the beginning sound programmer out there, so every code bit counts. What I really do not understand, is how to convert one format to another using the C API.

    Could you post an (incomplete), bare-bones example showing how to read one file (for instance FLAC) into a buffer, and then from this buffer write another file in another format (WAV or something else)?

    I would just need the absolute minimum (pseudo-?)code, no need for the includes, etc.

    Please? :)

  2. Angelos Says:

    hey, check this code that i wrote, using this code you can easily write a wave file, header, sub-header and data part everythign is explained along with the code, enjoy!!

    http://www.nerdmodo.com/2009/07/creating-recording-sound-in-wav-file-using-mimos-with-cc/


Leave a Reply