Skip to content

Instantly share code, notes, and snippets.

@kinoh
Created July 6, 2013 16:19
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 kinoh/5940365 to your computer and use it in GitHub Desktop.
Save kinoh/5940365 to your computer and use it in GitHub Desktop.
Convert gnuplot-like text data to wave format.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ROW_SIZE 1024
char header[44] = {
'R', 'I', 'F', 'F',
0, 0, 0, 0,
'W', 'A', 'V', 'E',
'f', 'm', 't', ' ',
0x10, 0, 0, 0,
1, 0,
1, 0,
0x44, 0xAC, 0, 0,
0x44, 0xAC, 0, 0,
0x01, 0,
0x08, 0,
'd', 'a', 't', 'a',
0, 0, 0, 0
};
int main(int argc, char *argv[])
{
FILE *input, *output;
int col;
double freq, max;
char row[ROW_SIZE];
int i;
int count, rate, written, size;
char *index, *next;
double data;
if (argc-1 < 5)
{
perror("Usage: wavwriter <input> <output> <column number> <max value> <frequency>");
exit(EXIT_FAILURE);
}
col = atoi(argv[3]);
max = atof(argv[4]);
freq = atof(argv[5]);
rate = (int)(freq / 44100 + 0.5);
input = fopen(argv[1], "r");
if (input == NULL)
{
perror(argv[1]);
exit(EXIT_FAILURE);
}
output = fopen(argv[2], "w");
if (output == NULL)
{
perror(argv[2]);
exit(EXIT_FAILURE);
}
fwrite(header, sizeof(char), sizeof(header) / sizeof(char), output);
count =
written = 0;
while (fgets(row, ROW_SIZE, input))
{
if (row[0] > '9')
continue;
index = row;
for (i = 1; i < col; i++)
{
index = strchr(index, ' ');
if (index == NULL)
goto TAIL;
while (index[0] == ' ')
index++;
}
next = strchr(index, ' ');
if (next != NULL)
*next = '\0';
data += atof(index);
count++;
if (count == rate)
{
fputc((char)((data / rate / (2. * max) + 0.5) * (1 << 8)), output);
data = 0;
count = 0;
written++;
}
TAIL: ;
}
fseek(output, 4, SEEK_SET);
size = written + 36;
fputc(size & 0xFF, output);
fputc((size >> 8) & 0xFF, output);
fputc((size >> 16) & 0xFF, output);
fputc((size >> 24), output);
fseek(output, 40, SEEK_SET);
size = written;
fputc(size & 0xFF, output);
fputc((size >> 8) & 0xFF, output);
fputc((size >> 16) & 0xFF, output);
fputc((size >> 24), output);
if (output == NULL)
{
perror(argv[2]);
exit(EXIT_FAILURE);
}
fclose(output);
fclose(input);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment