为什么我的.wav文件没有运行?

时间:2015-07-05 05:13:57

标签: c file audio wav wave

不使用结构,我正在尝试创建一个波形文件,以900 Hz的频率生成五秒钟的音调。但是,当我运行它时,它不会运行,甚至不会给我采样率或字节数。这是我的代码:

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

1 个答案:

答案 0 :(得分:1)

最明显的问题是Subchunk1ID "fmt"

那应该是"fmt ",注意最后的空格。