All pastes #2092849 Raw Edit

Anonymous

public c v1 · immutable
#2092849 ·published 2011-11-02 01:01 UTC
rendered paste body
#include <stdio.h>#include <termios.h>#include <math.h>#define A4 440#define HZ 8000.0#define PI 3.14159265float frequency(int note);void play(int note, float duration, float amplitude);char getch(void);int main() {	float amplitude = 0.5;	char keys[] = "awsedrfgyhujkolp;['\\";	int offset = 5;	char c;	int i;	while((c = getch()) != 4) {		for(i=0; i<sizeof(keys) / sizeof(keys[0]); i++) {			if(c == keys[i]) {				play(i - offset, 0.2, amplitude);			}		}	}	return 0;}char getch(void) {        char buf = 0;        struct termios old = {0};        if (tcgetattr(0, &old) < 0)                perror("tcsetattr()");        old.c_lflag &= ~ICANON;        old.c_lflag &= ~ECHO;        old.c_cc[VMIN] = 1;        old.c_cc[VTIME] = 0;        if (tcsetattr(0, TCSANOW, &old) < 0)                perror("tcsetattr ICANON");        if (read(0, &buf, 1) < 0)                perror ("read()");        old.c_lflag |= ICANON;        old.c_lflag |= ECHO;        if (tcsetattr(0, TCSADRAIN, &old) < 0)                perror ("tcsetattr ~ICANON");        return (buf);}float frequency(int note) {	return pow(2.0, note / 12.0) * A4;}void play(int note, float duration, float amplitude) {	int samples = (int)round(duration * HZ);	float freq = frequency(note);	float period = HZ / freq;	int v, x, s;	float n, i;	for(v=0; v<samples; v++) {			n = (1 + sin((v / period) * (PI * 2))) / 2;			x = (int)round(0xFF * n * amplitude);			putchar(x);	}}