Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
making audio from recursive sequences
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <assert.h>
#include <string.h>
#include <math.h>
void putu32(FILE* f, uint32_t x) {
for(int i = 0; i < 4; ++i) {
putc(x&0xFF, f);
x = x>>8;
}
}
void putu16(FILE* f, uint16_t x) {
for(int i = 0; i < 2; ++i) {
putc(x&0xFF, f);
x = x>>8;
}
}
int main(int argc, char** argv) {
FILE* f = stdout;
assert(f);
static const int sample_count = 4000;
static const uint32_t sample_rate = 4410;
static const float gain = 30.0;
int r[sample_count];
for(int i = 0; i < sample_count; ++i) r[i] = 1;
switch(argv[1][0]) {
case 'c':
for(int i = 3; i < sample_count; ++i) r[i] = r[i-r[i-1]] + r[i-r[i-2]];
for(int i = 0; i < sample_count; ++i) r[i] -= i/2;
break;
case 'e':
for(int i = 3; i < sample_count; ++i) r[i] = r[r[i-1]] + r[i-r[i-2]-1];
for(int i = 0; i < sample_count; ++i) r[i] -= i/2;
break;
case 'f':
for(int i = 3; i < sample_count; ++i) r[i] = r[r[i-1]] + r[i-2*r[i-2]+1];
for(int i = 0; i < sample_count; ++i) r[i] -= (int)(0.42*pow(i, 0.878));
break;
}
//set up sample rate and such
static const uint16_t channels = 1;
static const uint32_t bytes_per_sample = 2;
uint32_t data_size = sample_count *bytes_per_sample * channels;
//RIFF chunk
fprintf(f, "RIFF");
putu32(f, data_size + 36);
fprintf(f, "WAVE");
//fmt chunk
fprintf(f, "fmt ");
putu32(f, 16); //size of this chunk
putu16(f, 1); //1 = PCM
putu16(f, channels);
putu32(f, sample_rate);
putu32(f, sample_rate * bytes_per_sample * channels);
putu16(f, bytes_per_sample * channels);
putu16(f, bytes_per_sample * 8);
//data chunk
fprintf(f, "data");
putu32(f, data_size);
for(int sample = 0; sample < sample_count; ++sample) {
int x = r[sample] * gain;
uint16_t pcm_sample = (int16_t)(x);
putu16(f, pcm_sample);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment