(I did search for this, but didn't find exactly what I am looking for).

I am working on a function that will generate a sine wave at a given frequency AND sampling rate. Something that will "fill a 10k sample buffer with a 1 kHz wave at a 44.1 kHz sample rate".

My attempts so far are producing a "tone", but the tone changes in unexpected ways as I vary the inputs, and any reference along the lines of what I am trying to do might help.

I imagine that such a reference or a forum discussion might be "out there" somewhere. Appreciate any pointers....

(I did search for this, but didn't find exactly what I am looking for).

I am working on a function that will generate a sine wave at a given frequency AND sampling rate. Something that will "fill a 10k sample buffer with a 1 kHz wave at a 44.1 kHz sample rate".

My attempts so far are producing a "tone", but the tone changes in unexpected ways as I vary the inputs, and any reference along the lines of what I am trying to do might help.

I imagine that such a reference or a forum discussion might be "out there" somewhere. Appreciate any pointers....

I'm not aware of any simple reference for your specific question, but here's a quick line of thought for you:

  • A sample rate of 44.1 kHz is 44,100 samples/second
  • A 1 kHz wave is 1,000 cycles/second
  • The sine function has a cycle length of 2*pi

So. You need to scale your sine function such that 1,000 sine wave cycles would fit into 44,100 samples. Here's a rough look at how you'd derive code to fill the buffer:

for(i = 0; i < 10000; i++)
{
  // i is the sample index

  // Straight sine function means one cycle every 2*pi samples:
  // buffer[i] = sin(i); 

  // Multiply by 2*pi--now it's one cycle per sample:
  // buffer[i] = sin((2 * pi) * i); 

  // Multiply by 1,000 samples per second--now it's 1,000 cycles per second:
  // buffer[i] = sin(1000 * (2 * pi) * i);

  // Divide by 44,100 samples per second--now it's 1,000 cycles per 44,100
  // samples, which is just what we needed:
  buffer[i] = sin(1000 * (2 * pi) * i / 44100);
}

A graphing calculator will help you visualize what's going on in each step, and writing out the dimensional analysis can't hurt, either.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.