#include <stdio.h>
#include <stdlib.h>
#include "cdefs.h"
#include "wav_out.h"
static WAV_HEAD hdr =
{
FileChunkID: "RIFF",
RIFFType: "WAVE",
FmtChunkID: "fmt ",
dwFmtChunkLen: 16,
wCompression: WAVE_COMPRESSION_PCM,
DataChunkID: "data",
};
ssize_t WaveInitHeader(FILE* fp, int sample_rate, int bits_per_sample, int channels)
{
hdr.wChannels = channels;
hdr.dwSamplesPerSec = sample_rate;
hdr.dwAvgBytesPerSec = sample_rate * (bits_per_sample / 8 * channels);
hdr.wBlockAlign = bits_per_sample / 8 * channels;
hdr.wBitsPerSample = bits_per_sample;
hdr.dwFileChunkLen = sizeof(WAV_HEAD) - 8;
hdr.dwDataLen = 0;
return fwrite(&hdr, sizeof(hdr), 1, fp) == 1 ? sizeof(hdr) : 0;
}
ssize_t WaveWriteData(FILE* fp, void* buff, size_t size)
{
fseek(fp, 0, SEEK_END);
if (fwrite(buff, 1, size, fp) != size)
{
fprintf(stderr,"fwrite failed !/n");
return -1;
}
hdr.dwFileChunkLen += size;
hdr.dwDataLen += size;
fseek(fp, 0, SEEK_SET);
fwrite(&hdr, sizeof(hdr), 1, fp);
return size;
}
int WaveSync(FILE* fp)
{
if (hdr.dwDataLen & 1)
{
fseek(fp, 0, SEEK_END);
fputc(0, fp);
hdr.dwFileChunkLen++;
hdr.dwDataLen++;
fseek(fp, 0, SEEK_SET);
fwrite(&hdr, sizeof(hdr), 1, fp);
}
fflush(fp);
return 0;
}