Without using structures, I'm trying to create a wave file that generates a tone at 900 Hz for five seconds. When I run it, however, it doesn't run or even give me the sample rate or the number of bytes. Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main () {
FILE* fp;
fp = fopen("sine.wav", "wb");
if (fp == NULL) {
printf("File does not exist.\n");
return EXIT_FAILURE;
}
char ChunkID[4] = "RIFF", Format[4] = "WAVE", Subchunk1ID[4] = "fmt", Subchunk2ID[4] = "data";
unsigned int ChunkSize, Subchunk1Size, Subchunk2Size;
unsigned short int AudioFormat, NumChannels, BlockAlign, BitsPerSample;
int SampleRate, ByteRate;
Subchunk1Size = 16;
AudioFormat = 1;
NumChannels = 1;
SampleRate = 44100;
ByteRate = 2 * SampleRate;
BitsPerSample = 16;
BlockAlign = NumChannels * BitsPerSample / 8;
Subchunk2Size = 10 * ByteRate;
ChunkSize = Subchunk2Size + 41 - 8;
fwrite(ChunkID, 4, 1, fp);
fwrite(&ChunkSize, 4, 1, fp);
fwrite(Format, 4, 1, fp);
fwrite(Subchunk1ID, 4, 1, fp);
fwrite(&Subchunk1Size, 4, 1, fp);
fwrite(&AudioFormat, 2, 1, fp);
fwrite(&NumChannels, 2, 1, fp);
fwrite(&SampleRate, 4, 1, fp);
fwrite(&ByteRate, 4, 1, fp);
fwrite(&BlockAlign, 2, 1, fp);
fwrite(&BitsPerSample, 2, 1, fp);
fwrite(Subchunk2ID, 4, 1, fp);
fwrite(&Subchunk2Size, 4, 1, fp);
int i, amplitude = 37000;
short int audio;
float w, freq = 900 * 4;
w = 2.0 * M_PI * freq;
for(i = 0; i < 5 * SampleRate; i++) {
if (i < 5 * SampleRate / 4)
w = 900 * 4;
else
w = 0;
w *= 2.0 * M_PI;
audio = amplitude * sin(w * i / SampleRate);
fwrite(&audio, 2, 1, fp);
}
fclose(fp);
return EXIT_SUCCESS;
}
The most obvious problem is the Subchunk1ID
which you have as "fmt"
.
That should be "fmt "
, note the space at the end.