2
#include <stdio.h>
#include <string.h>

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);
}

谁能帮我解决这段代码中的问题。标题是正确的,它甚至正确地写在文件上。但是,每当打开 .wav 文件时,它都会显示一个额外的字段。而且文件也没有播放。如果我尝试使用媒体信息打开文件,它会按预期显示属性,但持续时间除外

格式:Wave 文件大小
:8.29 KiB 持续时间:20ms 总体比特率模式:恒定总体比特率
: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 采样率 : 8 000 Hz Bit depth
: 16比特流大小:320 字节 (4%)

4

1 回答 1

1

我对文件格式一无所知,但我很难相信它们会有一个二进制标头后跟 ascii 数据。所以我觉得 fgets 和 fputs 的使用是有问题的,因为 fgets 寻找一个 \n 终止符。因此,如果缓冲区在碰巧找到 \n ( 0xa ) 字节之前已填满,您可能会丢失数据。

while(!feof(fin))
{
    fgets(buffer,sizeof(buffer),fin);
    fputs(buffer,fout);
}

这样的事情会更有意义

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);
}

另外,为什么关闭 fout 然后重新打开它?

于 2013-11-11T03:13:40.960 回答