I'd like to create a .wav file containing a sound wave that starts at a certain frequency and fades to another frequency.
I believe that y = sin(2 * pi * x * f) will graph a sine wave of frequency f where x is time in seconds. So, I planned to just vary f.
Given freq_start & freq_end, then the change in frequency over time wave_length is:
y = (freq_end - freq_start) / wave_length * x + freq_start
Right? (Basic y = mx+b line)
So, I replaced f in the first equation with that. The resulting wave faded down in freqency, hit bottom, and when back up. I just want it to fade downwards. The code that does all this stuff is:
Code:
void write_short(FILE *fp, unsigned short i)
{
int x;
for(x = 0; x < 2; x++) fputc((i >> (x * 8)) & 0xFF, fp);
}
...
int main()
{
...
// Begin writing data:
freq_diff = freq_end - freq_start;
printf("Frequency difference is %d Hz.\n", freq_diff);
for(x = 0; x < SAMPLE_RATE * samp_time; x++)
{
ctime = (double) x / (double) SAMPLE_RATE;
hz = (double) freq_diff / (double) samp_time * ctime + (double) freq_start;
amp = sin(2.0 * M_PI * ctime * hz);
//printf("ctime = %g, hz = %g, amp = %g\n", ctime, hz, amp);
//scanf("%d", &y);
iamp = amp * 32767.0;
write_short(fp, (unsigned short) iamp);
}
fclose(fp);
return 0;
}
Compiles with no errors (Using gcc -Wall -o wavegen.exe wavegen.c) but gives a bad wave, as described above. ctime is gradually going up to the length, in seconds, of the wave file, as it should. Hz is gradually going down from freq_start to freq_end, again, as it should. SAMPLE_RATE is 44100. Yet the wave goes down in pitch, then back up. It should only go down. Full source is attached.