我正在尝试在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没有被正确写入。
此帖子来自Creating a stereo WAV file using C。
我试图对一些结构值进行硬编码,因为我总是使用44.1K采样率并始终使用2个通道(其中一个通常是空白数据)。