Skip to content

Instantly share code, notes, and snippets.

@adituv
Last active December 26, 2015 15:38
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 adituv/7173733 to your computer and use it in GitHub Desktop.
Save adituv/7173733 to your computer and use it in GitHub Desktop.
Very simple converter from list of frequencies and durations to output sound wave on stdout. Pipe it through e.g. /dev/audio or aplay to actually create sound.
1.25@130.8127827
0.25@174.6141157
0.25@164.8137785
0.25@174.6141157
0.75@195.9977180
0.25@207.6523488
1.00@195.9977180
1.25@0
0.25@174.6141157
0.25@195.9977180
0.25@174.6141157
0.50@220
1.00@261.6255653
0.50@311.1269837
0.50@311.1269837
0.50@349.2282314
0.50@277.1826310
0.50@261.6255653
0.75@233.0818808
0.25@261.6255653
0.50@277.1826310
0.50@311.1269837
2.00@261.6255653
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
const int freq = 8000; // aimed at 8kHz output
const int ampl = 255;
typedef struct LinkedList {
uint64_t length;
double frequ;
struct LinkedList* next;
} LinkedList_t;
LinkedList_t* addNote(LinkedList_t* notelist, double duration, double pitch);
void playSound(LinkedList_t* sound);
int main(void) {
double dur = 0.0, pitch = 0.0;
LinkedList_t* baseList = NULL;
LinkedList_t* curList = NULL;
if(!(baseList = malloc(sizeof (LinkedList_t)))) {
fprintf(stderr, "Unexpected memory error. Maybe you're out of memory?\n");
abort();
}
curList = baseList;
while(1) {
dur = 0.0, pitch = 0.0;
scanf("%lf@%lf", &dur, &pitch);
if(!feof(stdin)) {
if(dur <= 0.0f || pitch < 0.0f || pitch > 20000.0f) {
fprintf(stderr, "Invalid entry. Please enter in the form duration@pitch.\n");
while(fgetc(stdin) != '\n');
continue;
}
if(curList = addNote(curList, dur, pitch))
continue;
else {
fprintf(stderr, "Unexpected memory error. Maybe you're out of memory?\n");
abort();
}
} else {
break;
}
}
//When stdin is closed, play back music
curList = baseList;
while(curList != NULL) {
LinkedList_t* prevList = NULL;
playSound(curList);
prevList = curList;
curList = curList->next;
free(prevList);
}
}
LinkedList_t* addNote(LinkedList_t* list, double duration, double frequency) {
if(list->next = malloc(sizeof (LinkedList_t))) {
list->next->length = ceil(duration * freq);
list->next->frequ = frequency;
}
return list->next;
}
void playSound(LinkedList_t* sound) {
int i = 0;
for(i = 0; i < sound->length; ++i) {
int sample = signbit(sin(2.0*M_PI*sound->frequ*i/freq));
putchar(sound->frequ == 0.0 ? 128 : 255 * sample);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment