问题
I am trying to create a stereo sine WAV in C, with the possibility to have a different (and possibly blank) left and right channels.
A tone is generated for each channel with this function:
int16_t * create_tone(float frequency, float amplitude, float duration)
I then open a FILE*
and call create_wav
. Here are the two structures I'm using to create the 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;
};
And here's the actual function to create the WAV file:
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;
}
}
Unfortunately, I'm getting a small (4K or 8K only file), so I suspect the actual WAV_data isn't being written properly.
This post follows on from Creating a stereo WAV file using C.
I'm trying to hard code some of the structure values, as I'm always using a 44.1K sample rate and always using 2 channels (one of them is sometimes fed blank data).
来源:https://stackoverflow.com/questions/23146798/creating-a-stereo-sin-wav-using-c