使用C创建立体声sin WAV

我试图在C中创建一个立体声正弦波WAV,可能有一个不同的(可能是空白的)左右声道。

使用此function为每个通道生成一个音调:

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文件的实际function:

 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个通道(其中一个通常是空白数据)。