audiocore-audioportaudiosound-synthesis

Generate sine wave to play middle C using PortAudio


I am having trouble generating specific frequencies in PortAudio, whenever I try and change the frequency inside of the sin(n * FREQ * 2 * PI / SAMPLE_RATE) the frequency remains the same however the sound does seem to change in timbre, the higher the frequency value I put in there the uglier the sound, yet the same frequency. This is what I have in my patestCallback loop:

static int patestCallback( const void *inputBuffer, void *outputBuffer,
                           unsigned long framesPerBuffer,
                           const PaStreamCallbackTimeInfo *timeInfo,
                           PaStreamCallbackFlags statusFlags,
                           void *userData )
{
   paTestData *data = (paTestData*)userData;
   float *out = (float*)outputBuffer;

   (void) timeInfo;
   (void) statusFlags;
   (void) inputBuffer;
   unsigned long n = 0;
   for(unsigned long i = 0; i<framesPerBuffer;i++,n++){
      float v = sin ( 261.626 * 2 * M_PI * ((float) n / (float) TABLE_SIZE) );
      *out++ = v;
      *out++ = v;
   }

   return paContinue;
}

Solution

  • Simple solution:

    static unsigned long n = 0;
    

    You currently reset n in every function call, which leads to clicks at the begin of each new buffer and to those ugly sounds you hear. The more the period of the sine differs from the buffer length the uglier it sounds.