-
Tone generation
Hello,
As this neither language- nor platform-specific, I'll post this here. I'm looking into making a tone generator program. As far as I can tell, this involves generating sine waves at different frequencies and amplitudes, a bit like so:-
Code:
int i;
double scale;
unsigned char ucBuffer[48000]; //48KHz sampling rate, 8-bit mono
unsigned char *pData;
scale = (2 * PI) / 48000;
pData = ucBuffer;
for (i=0;i<48000;i++)
*(pData++) = (unsigned char)sin(i * scale);
However, when I pass this to an output device, I either hear nothing at all or some weird "clicking" or "popping". Am I going deaf? :rolleyes:
I know the code above is too simple to produce anything meaningful, but I'm heading in the right direction, aren't I?
-
>(unsigned char)sin(i * scale);
You are using an unsigned char to store your value. Note that the maximum value of the sine-wave is 1 and the minimum is -1. Values between will be rounded off to 0 or 1, because the variable is unsigned.
Try this: use a char instead of an unsigned char and give the sine-wave an amplitude larger than 1. Perhaps you could also do some debugging by writing the signal to a file so that you can see which values were calculated.
-
Ah yes, forgot about that, thanks Shiro ;)
It does generate a sine wave "sound" now, at least after multiplying it with the upper positive and negative limit of a char (127). Now if I can work out how to stop this infernal "popping" after each play (I've even tried splitting the data into two half-second buffers, but to no avail...) :(