Search code examples
c++audiobufferwavlibsndfile

Writing to one channel at a time in libsndfile


I'm trying to generate a sine wave that switches between the left and right channels of a stereo wav file at 1 second intervals, but I can't find any way to write to one channel while keeping the other one silent. Here is the code I've got to write to one channel:

for (int f = 0; f < numFrames; f++) {
    double time = f * duration / numFrames;
    buffer[f] = sin(2.0 * pi * time * freq);

And here's some code I found that can be used to mix two mono wav files together:

short* mixdown = new short[2 * sizeof(short) * 800000];
for (int t = 0; t < 800000 * 2; ++t) {
    mixdown[t] = (buffer1[t] + buffer2[t]) / 2;
}

FILE* process2 = _popen("ffmpeg -y -f s16le -acodec pcm_s16le -ar 44100 -ac 2 -i - -f vob -ac 2 D:\\audioMixdown.wav", "wb");
fwrite(mixdown, 2 * sizeof(short) * 800000, 1, process2);

I've looked through the libsndfile API at http://www.mega-nerd.com/libsndfile/api.html but couldn't find anything on writing to channels. If anyone has any ideas what the best way to go about doing this would be, I would love to hear your input.


Solution

  • You can achieve this by just writing zero samples to the 'silent' channel, e.g. (to silence the right-hand channel):

    for (int f = 0; f < numFrames; f++)
    {
        double time = f * duration / numFrames;
        buffer[f * 2] = sin(2.0 * pi * time * freq);
        buffer[f * 2 + 1] = 0;
    }
    

    This assumes that libsndfile expects channel data in interleaved format (which I believe is true but am not certain of).