[LAD] mixing while using libao and libsndfile

David Griffith dave at 661.org
Mon May 16 22:25:48 UTC 2016

On Mon, 16 May 2016, Andrea Del Signore wrote:

> > I've been knocking my head against a wall for more than a year trying to
> > figure out how to correctly mix two streams of audio while using
> > libsndfile for input and libao for output.  My main requirement is that
> > I cannot assume anything about the output drivers -- that is, I cannot
> > depend on the output driver (ALSA, OSS, Sun, etc) being able to do the
> > mixing for me.  Many of my target platforms lack any sort of mixing
> > services.  I need to do this myself.  I tried starting a mixer/player
> > thread that would work in a producer/consumer relationship with one or
> > two audio file decoder threads.  I can play one sound at a time just
> > fine. When I try to do both, I get distortion followed by a segfault.
> Hi,
> not sure if I understood correctly: do you just want to mix N files?
> Like you I'm learning libsndfile and libao so this is my attempt to mix some audio files:
> http://pastebin.com/dm7z8b3Z
> HTH,
> Andrea
> P.S.
> Can someone explain line 88 (I already read the sndfile FAQ)?

I'm not simply trying to mix two files.  My main project is a game engine 
in which two sounds are allowed at any one time.  For instance, there can 
be constant background music punctuated by sound effects.  I can't get 
these to mix correctly.

Regarding your line 88, I had trouble with this too:

sf_count_t item_read = sf_read_float (sndfile[i], filebuffer, BUFFSIZE); 
// WHY BUFFSIZE? Shouldn't be BUFFSIZE * channels?

The third parameter is for the number of items or frames.  A frame is made 
up of one sample per channel.  Earlier you set up filebuffer like this:

buflen = BUFFSIZE * sf_info[0].channels;
filebuffer = malloc(buflen * sizeof(float));

The size of filebuffer is BUFFSIZE float-sized frames.  Therefore when you 
specify BUFFSIZE as the number of floats to read, they all fit in 

David Griffith
dave at 661.org

More information about the Linux-audio-dev mailing list