Last active
December 26, 2015 15:38
-
-
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.
This file contains 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
This file contains 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 <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