0

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.

2 Answers2

1

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).

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48
1

Assuming the channels are interleaved in the buffer, do:

for (int f = 0; f < numFrames; f+=2) {
    ...
    int odd = seconds % 2;
    buffer[f+odd] = sin(2.0 * pi * time * freq);
    buffer[f+1-odd] = 0.0;
stark
  • 12,615
  • 3
  • 33
  • 50