-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbabySynth.pde
103 lines (91 loc) · 2.35 KB
/
babySynth.pde
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import processing.sound.*;
final double SEMITONE_RATIO = pow(2.0, (1.0 / 12.0));
float frequency;
double root = 110.0;
boolean playing = false;
char lastKey = ' ';
StringList keysPressed;
SqrOsc wave;
PFont font;
String note;
Env env;
float attackTime = 0.0001;
float sustainTime = 0.1;
float sustainLevel = 0.1;
float releaseTime = 0.2;
// The home row is the white keys, with a = A, d = D, r = C#.
// String keys = new String("awsdrftghujikol;[']");
// Two rows of white and black keys, z = A, c = C, f = C#.
String keys = new String("zsxcfvgbnjmk,l./'q2we4r5t6yu8i9op");
// Chromatic
// String keys = new String("zxcvbnm,./asdfghjkl;'qwertyuiop[]1234567890");
String[] notes = {"A", "A\u266F", "B", "C", "C\u266F", "D", "D\u266F", "E", "F", "F\u266F", "G", "G\u266F"};
float tune(double currentFrequency, int intervalSemitones) {
double newFrequency = currentFrequency;
for (int i = 0; i < intervalSemitones; i++) {
newFrequency = newFrequency * SEMITONE_RATIO;
}
if (intervalSemitones < 0) {
intervalSemitones = intervalSemitones * -1;
for (int i = 0; i < intervalSemitones; i++) {
newFrequency = newFrequency / SEMITONE_RATIO;
}
}
return (float) newFrequency;
}
void keyPressed() {
println("keypressed: " + key);
if (key == '+' || key == '=') {
root = root * 2;
}
if (key == '-') {
root = root / 2;
}
if (playing && (key == lastKey)) {
return;
}
if (playing) {
playing = false;
}
if (keys.indexOf(key) != -1) {
int keyInterval = keys.indexOf(key);
frequency = tune(root, keyInterval);
note = notes[keyInterval % 12];
println(note + " : " + frequency);
wave.play(frequency, 0.6);
env.play(wave, attackTime, sustainTime, sustainLevel, releaseTime);
playing = true;
}
lastKey = key;
}
void keyReleased() {
if (!keyPressed) {
println("stopping: " + key);
note = "";
playing = false;
}
}
void setup() {
println(SEMITONE_RATIO);
size(640, 360);
keysPressed = new StringList();
font = createFont("Open Sans", 48, true);
env = new Env(this);
float volume = 1;
wave = new SqrOsc(this);
wave.amp(volume);
frequency = tune(root, 0);
}
void draw() {
if (!keyPressed && playing) {
println("stopping");
playing = false;
}
background(0);
if (playing) {
textFont(font);
fill(255);
textAlign(CENTER, CENTER);
text(note, 320, 180);
}
}