我的实际项目涉及更多,但我相信如果我可以解决这个更简单的代码,我将能够让我的项目完全正常工作。标题信息和我写的字节数,我的期望和打印到屏幕上的信息都有意义,但是在打开wav文件时,会遇到错误并显示错误。从第45个字节开始,只写入短零,这意味着整个wav文件只是静默。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main()
{ int i;
typedef struct h{
char ChunkID[4]; /*RIFF*/
unsigned int ChunkSize;
char format[4]; /*WAVE*/
char SubChunk1ID[4]; /*fmt*/
unsigned int SubChunk1Size;
unsigned short int AudioFormat;
unsigned short int NumChannels;
unsigned int SampleRate;
unsigned int ByteRate;
short int BlockAlign;
short int BitsPerSample;
char SubChunk2ID[4];
unsigned int SubChunk2Size;
}rtz;
/*start of filling out the information we know*/
rtz HeaderOut;
HeaderOut.SampleRate = 44100;
HeaderOut.NumChannels = 1;
HeaderOut.BitsPerSample = 16;
strcpy(HeaderOut.ChunkID,"RIFF");
strcpy(HeaderOut.format,"WAVE");
strcpy(HeaderOut.SubChunk1ID,"fmt");
strcpy(HeaderOut.SubChunk2ID,"data");
HeaderOut.AudioFormat = 1;
HeaderOut.ChunkSize = 1411236;
HeaderOut.SubChunk2Size = 1411200;
HeaderOut.SubChunk1Size = 16;
HeaderOut.ByteRate = HeaderOut.SampleRate*HeaderOut.NumChannels*HeaderOut.BitsPerSample/8;
HeaderOut.BlockAlign = HeaderOut.NumChannels*HeaderOut.BitsPerSample/8;
printf("ChunkID = RIFF %d bytes\n", sizeof(HeaderOut.ChunkID));
printf("Chunksize = %d %d bytes\n",HeaderOut.ChunkSize,sizeof(HeaderOut.ChunkSize));
printf("format = WAVE %d bytes\n",sizeof(HeaderOut.format));
printf("SubChunk1ID = %s %d bytes\n",HeaderOut.SubChunk1ID,sizeof(HeaderOut.SubChunk1ID));
printf("SubChunkSize = %d %d bytes\n",HeaderOut.SubChunk1Size,sizeof(HeaderOut.SubChunk1Size));
printf("AudioFormat = %d %d bytes\n",HeaderOut.AudioFormat,sizeof(HeaderOut.AudioFormat)); /* AUDIOFORMAT CHANGES*/
printf("NumChannels = %d %d bytes\n",HeaderOut.NumChannels,sizeof(HeaderOut.NumChannels));
printf("SampleRate = %d %d bytes\n",HeaderOut.SampleRate,sizeof(HeaderOut.SampleRate));
printf("ByteRate = %d %d bytes\n",HeaderOut.ByteRate,sizeof(HeaderOut.ByteRate));
printf("BlockAlign = %d %d bytes\n",HeaderOut.BlockAlign,sizeof(HeaderOut.BlockAlign));
printf("BitsPerSample = %d %d bytes\n", HeaderOut.BitsPerSample,sizeof(HeaderOut.BitsPerSample));
printf("SubChunk2ID = data %d bytes\n",sizeof(HeaderOut.SubChunk2ID));
printf("SubChunk2Size = %d %d bytes\n\n",HeaderOut.SubChunk2Size,sizeof(HeaderOut.SubChunk2Size));
printf("Size of HeaderOut = %d bytes\n", sizeof(HeaderOut));
printf("\n");
FILE *fp;
fp = fopen("experiment.wav","wb");
if(fp == NULL){printf("File did not open successfully.\n");
}else{
fwrite(&HeaderOut,44,1,fp);
printf("File successfully opened.\n");
short int silence[14700];
for (i = 0; i<14700 ; i++){
silence[i] = 0;
}
for (i = 0 ; i<48; i++){
fwrite(silence, sizeof( short int), 14700,fp);
}
fclose(fp);
}/*end of else statement*/
}/*end of MAIN */