-2

I'm trying to generate a simple sine wave in rtaudio to verify I understand what's going on. However, it is coming out wrong.

I have a global float timec, and a callback invoked with openStream which should fill a buffer with samples.

float freq = 440; // center frequency
int SAMPLE_RATE = 44100;
for (int i = 0; i < numFrames; i++) {
    float v = sin(2 * M_PI * freq * (timec / SAMPLE_RATE));
    outputbuffer[i] = v;
    timec++;
}

What have I done wrong? Instead of a sine wave, I hear a low grinding sound.

Ren Zhou
  • 11
  • 1
  • 2
  • Use your debugger, and have your debugger show the value of `timec / SAMPLE_RATE`. When `timec` is 1, for example, `1 / 44100` is zero. And the result of that division is going to be zero until `timec` reaches the value of 44100. Sp, the first 44100 samples will be computed as `sin(0)`. That's how C++ works. – Sam Varshavchik Oct 04 '17 at 00:59
  • @SamVarshavchik Since timec is a float, shouldn't it automatically promote the result? – Ren Zhou Oct 04 '17 at 01:02
  • Where did you get that `timec` is a float? The declaration of `timec` is not given in the shown code, and was presumed to be `int`. – Sam Varshavchik Oct 04 '17 at 01:04

1 Answers1

0

Answering my own question.

Rtaudio handles the output buffer in a tricky way. The array of floats is not for a single mono channel, it contains slots representing one frame for each channel, followed by several slots for the next frame, etc. The key correction, since this output has 2 channels, is:

outputbuffer[2 * i] = v;

to output on just one channel.

Ren Zhou
  • 11
  • 1
  • 2