-1

I'm following along with The Audio Programming Book by Richard Boulanger. In Chapter two we create several basic audio rate oscillators using C and the standard libraries to generate simple WAV files.

Both my implementation and the book's code exhibit a strange issue:

I am able to generate a simple sine wave using sin() (from math.h), but noticed the playback has a bit of static. Upon investigation I noticed that occasionally, some of the audio frames at peak amplitude are getting "flipped" to a negative value.

To debug this situation, I'm outputting the values of the audio frames generated to stdout and this flipping behavior lines up with the peak value of 0.999999.

When I scale the output by 0.99 this problem disappears. What's going on?

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76

1 Answers1

0

Looking at siggen.c I was able to find the real problem has to do with the maximum value conversion to short datatype:

portsf.c:78
#define MAX_16BIT (32768.0)

portsf.c:1618
ssamp = (short) psf_round(fsamp * MAX_16BIT);

When we have a float sample near 1.0 this results in the conversion (short)(32768). Given that a short can only hold up to 32767 the value gets wrapped to the smallest short possible, -32768.

To fix this, I suggest modifying line 1618 to instead read:

ssamp = (short) psf_round(fsamp * 32767.0);

This will reduce the peak-to-peak value range by 1, but well worth avoiding this problem in my opinion