Created
February 28, 2018 04:47
-
-
Save hosackm/9af4d09d7f9f9950e6fc774010e2d874 to your computer and use it in GitHub Desktop.
Encode signed 16 bit 16 kHz PCM to FLAC file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "FLAC/stream_encoder.h" | |
#define CHUNKSIZE 512 | |
FLAC__StreamEncoderWriteStatus callback | |
(const FLAC__StreamEncoder *encoder | |
,const FLAC__byte buffer[] | |
,size_t bytes | |
,unsigned samples | |
,unsigned current_frame | |
,void *client_data) | |
{ | |
/* write to file */ | |
FILE *output_file = (FILE*) client_data; | |
fprintf(stdout, "writing %d bytes\n", samples); | |
fwrite((void*)buffer, 1, bytes, output_file); | |
return FLAC__STREAM_ENCODER_WRITE_STATUS_OK; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
FLAC__int16 buffer[CHUNKSIZE]; | |
FLAC__int32 flac_buffer[CHUNKSIZE]; | |
FLAC__int32 const *flac_buffers[] = {flac_buffer}; | |
FLAC__StreamEncoder *p_enc = FLAC__stream_encoder_new(); | |
/* open output file */ | |
FILE *output_file = fopen("output.flac", "w+b"); | |
if(!output_file) | |
{ | |
fprintf(stderr, "Error opening output file\n"); | |
return -1; | |
} | |
/* initialize the encoder and stream callback function */ | |
FLAC__stream_encoder_set_channels(p_enc, 1); | |
FLAC__stream_encoder_set_bits_per_sample(p_enc, 16); | |
FLAC__stream_encoder_set_sample_rate(p_enc, 16000); | |
FLAC__stream_encoder_init_stream(p_enc, callback, NULL, NULL, NULL, output_file); | |
/* process entire file */ | |
FILE *input_file = fopen("vice.pcm", "r+b"); | |
if(!input_file) | |
{ | |
fprintf(stderr, "Error opening input file\n"); | |
return -1; | |
} | |
/* process entire pcm file */ | |
for(;;) | |
{ | |
/* try to read a full chunk */ | |
const size_t num_read = fread(buffer, sizeof(FLAC__int16), CHUNKSIZE, input_file); | |
/* check for EOF */ | |
if(num_read == 0) | |
{ | |
break; | |
} | |
/* cast FLAC__int16 to a buffer of FLAC__int32 */ | |
for(int i = 0; i < num_read; ++i) | |
{ | |
flac_buffer[i] = (FLAC__int32)buffer[i]; | |
} | |
/* process the buffer */ | |
fprintf(stdout, "processing %zu (16-bit/2-byte) samples\n", num_read); | |
FLAC__stream_encoder_process(p_enc, flac_buffers, CHUNKSIZE); | |
} | |
/* finish and clean up */ | |
FLAC__stream_encoder_finish(p_enc); | |
FLAC__stream_encoder_delete(p_enc); | |
fclose(output_file); | |
fclose(input_file); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment