将PCM 16位LE转换为WAV

时间:2012-12-14 15:27:09

标签: c audio wav pcm sox

我正在尝试用C编写一个程序,将捕获的 Raw 16kHz PCM 16位文件转换为 16位WAV

我看了一些帖子,推荐使用libsox的人。安装它,现在我真的很难理解man-page

到目前为止(通过阅读源码中的示例)我已经发现structs

  • sox_format_t
  • sox_signalinfo_t

可能用于描述我正在输入的数据。如果有必要,我也知道我正在处理多少信息(时间)?

赞赏一些指导!

2 个答案:

答案 0 :(得分:4)

嗯,问题得到解答后,问题就解决了。但是我会在这里发布代码,以便人们可以分析它或者只是在他们自己的项目中使用它。

" simonc"提供的链接和" Nickolay O。"被使用了。在网上搜索有关各个字段的更多信息。

struct wavfile
{
    char        id[4];          // should always contain "RIFF"
    int     totallength;    // total file length minus 8
    char        wavefmt[8];     // should be "WAVEfmt "
    int     format;         // 16 for PCM format
    short     pcm;            // 1 for PCM format
    short     channels;       // channels
    int     frequency;      // sampling frequency, 16000 in this case
    int     bytes_per_second;
    short     bytes_by_capture;
    short     bits_per_sample;
    char        data[4];        // should always contain "data"
    int     bytes_in_data;
};

//Writes a header to a file that has been opened (take heed that the correct flags
//must've been used. Binary mode required, then you should choose whether you want to 
//append or overwrite current file
void write_wav_header(char* name, int samples, int channels){
    struct wavfile filler;
    FILE *pFile;
    strcpy(filler.id, "RIFF");
    filler.totallength = (samples * channels) + sizeof(struct wavfile) - 8; //81956
    strcpy(filler.wavefmt, "WAVEfmt ");
    filler.format = 16;
    filler.pcm = 1;
    filler.channels = channels;
    filler.frequency = 16000;
    filler.bits_per_sample = 16;
    filler.bytes_per_second = filler.channels * filler.frequency * filler.bits_per_sample/8;
    filler.bytes_by_capture = filler.channels*filler.bits_per_sample/8;
    filler.bytes_in_data = samples * filler.channels * filler.bits_per_sample/8;    
    strcpy(filler.data, "data");
    pFile = fopen(name, "wb");
    fwrite(&filler, 1, sizeof(filler), pFile);
    fclose(pFile);
}

答案 1 :(得分:1)

我建议手动编写WAV标题和数据,这对PCM来说非常简单:https://ccrma.stanford.edu/courses/422/projects/WaveFormat/