Skip to content

Instantly share code, notes, and snippets.

@lalawue
Created January 28, 2015 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lalawue/4ef9fbb13034c774722d to your computer and use it in GitHub Desktop.
Save lalawue/4ef9fbb13034c774722d to your computer and use it in GitHub Desktop.
Read .wav audio file format and save the raw data
/*
* Copyright (c) 2015 lalawue
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MIT license. See LICENSE for details.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
static char* _read_file(const char* fileName) {
FILE *fp = fopen(fileName, "rb");
assert( fp );
fseek(fp, 0, SEEK_END);
long len = ftell(fp);
char *data = (char*)malloc(len+1);
assert(data);
memset(data, 0, len+1);
rewind(fp);
fread(data, 1, len, fp);
fclose(fp);
return data;
}
int _is_chunk(char *b, char *s) {
int i;
for (i=0; i<strlen(s); i++)
if (b[i] != s[i]) return 0;
return 1;
}
unsigned int _to_dword(char *buf) {
return *(unsigned int*)buf;
}
unsigned short _to_word(char *buf) {
return *(unsigned short*)buf;
}
void _dump_buf(char *buf) {
int i;
for (i=0; i<32; i++) {
if (i && (i%16==0)) {
printf("\n");
}
printf("%02x ", buf[i]);
}
printf("\n");
}
void _save_file(char *fname, char *buf, int buf_len) {
FILE *fp = fopen(fname, "wb");
if (fp) {
fwrite(buf, 1, buf_len, fp);
fclose(fp);
}
}
int main(int argc, char *argv[]) {
if (argc < 3) {
printf("%s wav_file save_file\n", argv[0]);
return 0;
}
char *buf = _read_file(argv[1]);
unsigned int size = 0;
if (_is_chunk(buf, "RIFF")) {
buf += 4;
size = _to_dword(buf);
buf += 4;
printf("RIFF:%d\n", size);
} else assert(0);
if (_is_chunk(buf, "WAVE")) {
buf += 4;
} else assert(0);
if (_is_chunk(buf, "fmt ")) {
buf += 4;
size = _to_dword(buf);
buf += 4;
printf("fmt :%d\n", size);
/* */
printf("formatTag:%d\n", _to_word(buf));
buf += 2;
printf("channels:%d\n", _to_word(buf));
buf += 2;
printf("samplePerSec:%d\n", _to_dword(buf));
buf += 4;
printf("AvgBytePerSec:%d\n", _to_dword(buf));
buf += 4;
printf("BlockAlign:%d\n", _to_dword(buf));
buf += 2;
printf("BytePerSample:%d\n", _to_dword(buf));
buf += 2;
if (size == 18) {
buf += 2;
}
} else assert(0);
if (_is_chunk(buf, "LIST")) {
buf += 4;
size = _to_dword(buf);
buf += 4;
printf("list :%d\n", size);
buf += size;
} else assert(0);
if (_is_chunk(buf, "data")) {
buf += 4;
size = _to_dword(buf);
buf += 4;
printf("data :%d\n", size);
_save_file(argv[2], buf, size);
} else assert(0);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment