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.