创建采用C立体声罪WAV(Creating a stereo sin WAV using C)

2019-10-19 22:12发布

我想创建一个在C立体声正弦WAV,与可能有不同的(也可能是空)左,右声道。

音调被用于与该函数中的每个信道生成的:

int16_t * create_tone(float frequency, float amplitude, float duration)

然后我打开一个FILE* ,并调用create_wav 。 下面是我用来创建WAV两种结构:

struct wav_h
{
    char    ChunkID[4];
    int32_t ChunkSize;
    char    Format[4];

    char    Subchunk1ID[4];
    int32_t Subchunk1Size;
    int16_t AudioFormat;
    int16_t NumChannels;
    int32_t SampleRate;
    int32_t ByteRate;
    int16_t BlockAlign;
    int16_t BitsPerSample;

    char    Subchunk2ID[4];
    int32_t Subchunk2Size;
};

struct pcm_snd
{
    int16_t channel_left;
    int16_t channel_right;
};

而这里的实际功能来创建WAV文件:

int create_wav_file(FILE* file, int16_t* tonel, int16_t* toner, int toneduration)
{
    /* Create WAV file header */

    struct wav_h wav_header;
    size_t wc;
    int32_t fc = toneduration * 44100;

    wav_header.ChunkID[0] = 'R';
    wav_header.ChunkID[1] = 'I';
    wav_header.ChunkID[2] = 'F';
    wav_header.ChunkID[3] = 'F';
    wav_header.ChunkSize = 4 + (8 + 16) + (8 + (fc * 2 * 2)); /* 4 + (8 + subchunk1size_ + (8 + subchunk2_size) */

    wav_header.Format[0] = 'W';
    wav_header.Format[1] = 'A';
    wav_header.Format[2] = 'V';
    wav_header.Format[3] = 'E';

    wav_header.Subchunk1ID[0] = 'f';
    wav_header.Subchunk1ID[1] = 'm';
    wav_header.Subchunk1ID[2] = 't';
    wav_header.Subchunk1ID[3] = ' ';

    wav_header.Subchunk1Size = 16;
    wav_header.AudioFormat = 1;
    wav_header.NumChannels = 2;
    wav_header.SampleRate = 44100;
    wav_header.ByteRate = (44100 * 2 * 2); /* sample rate * number of channels * bits per sample / 8 */
    wav_header.BlockAlign = 1; /* number of channels / bits per sample / 8 */
    wav_header.BitsPerSample = 16;

    wav_header.Subchunk2ID[0] = 'd';
    wav_header.Subchunk2ID[1] = 'a';
    wav_header.Subchunk2ID[2] = 't';
    wav_header.Subchunk2ID[3] = 'a';
    wav_header.Subchunk2Size = (fc * 2 * 2); /* frame count * number of channels * bits per sample / 8 */

    /* Write WAV file header */

    wc = fwrite(&wav_header, sizeof(wav_h), 1, file);
    if (wc != 1)
        return -1;
    wc = 0;

    /* Create PCM sound data structure */

    struct pcm_snd snd_data;
    snd_data.channel_left = *tonel;
    snd_data.channel_right = *toner;

    /* Write WAV file data */
    wc = fwrite(&snd_data, sizeof(pcm_snd), fc, file);

    if(wc < fc)
    {
        return -1;
    }
    else
    {
        return 0;
    }
}

不幸的是,我发现了一个小(4K或8K仅文件),所以我怀疑实际WAV_data没有被正确写入。

从这个职位上遵循创建采用C立体声WAV文件 。

我试图硬编码的一些结构的值,因为我总是使用44.1K采样速率,总是使用2个信道(其中一个被送入有时空白数据)。

文章来源: Creating a stereo sin WAV using C