#include
#include
int main() {
FILE *fin,*fout;
char buffer[1028];
int readcount=0;
short NumChannels = 1;
short BitsPerSample = 16;
int SamplingRate =8000;
short numOfSamples = 160;
int ByteRate = NumChannels*BitsPerSample*SamplingRate/8;
short BlockAlign = NumChannels*BitsPerSample/8;
int DataSize = NumChannels*numOfSamples * BitsPerSample/8;
int chunkSize = 16;
int totalSize = 36 + DataSize;
short audioFormat = 1;
if((fout = fopen("sample.wav", "w")) == NULL)
{
printf("Error opening out file ");
}
//totOutSample = 0;
fwrite("RIFF", sizeof(char), 4,fout);
fwrite(&totalSize, sizeof(int), 1, fout);
fwrite("WAVE", sizeof(char), 4, fout);
fwrite("fmt ", sizeof(char), 4, fout);
fwrite(&chunkSize, sizeof(int),1,fout);
fwrite(&audioFormat, sizeof(short), 1, fout);
fwrite(&NumChannels, sizeof(short),1,fout);
fwrite(&SamplingRate, sizeof(int), 1, fout);
fwrite(&ByteRate, sizeof(int), 1, fout);
fwrite(&BlockAlign, sizeof(short), 1, fout);
fwrite(&BitsPerSample, sizeof(short), 1, fout);
fwrite("data", sizeof(char), 4, fout);
fwrite(&DataSize, sizeof(int), 1, fout);
fclose(fout);
fin=fopen("sample.raw","r");
fout=fopen("sample.wav","a");
while(!feof(fin))
{
fgets(buffer,sizeof(buffer),fin);
fputs(buffer,fout);
}
fclose(fin);
fclose(fout);
}
Can anyone help me to solve the problem in this code. Header is proper and its even properly written on file. But whenever opening in frhed the .wav file, its showing one extra field. And also file is not playing. If I try opening the file using media info its showing properties as expected except duration
Format : Wave File size
: 8.29 KiB Duration : 20ms Overall bit
rate mode : Constant Overall bit rate
: 3 394 Kbps
Audio Format : PCM Format settings,
Endianness : Little Format settings, Sign
: Signed Codec ID : 1 Duration
: 20ms Bit rate mode : Constant Bit rate
: 128 Kbps Channel(s) : 1 channel
Sampling rate : 8 000 Hz Bit depth
: 16 bits Stream size : 320 Bytes (4%)
解决方案
I know nothing about the file formats, but I find it hard to believe they would have a binary header followed by ascii data. So the use of fgets and fputs I find questionable since fgets looks for a \n terminator. So you could be losing data if the buffer fills up before it happens to find a \n ( 0xa ) byte.
while(!feof(fin))
{
fgets(buffer,sizeof(buffer),fin);
fputs(buffer,fout);
}
Something like this would make more sense
size_t n;
while((n = fread(buffer, 1, sizeof(buffer), fin)) > 0) {
if(n != fwrite(buffer, 1, n, fout)) {
perror("fwrite");
exit(1);
}
}
if(n < 0) {
perror("fread");
exit(1);
}
Also, why do you close fout and then reopen it?