-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.py
More file actions
101 lines (80 loc) · 2.61 KB
/
controller.py
File metadata and controls
101 lines (80 loc) · 2.61 KB
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
import mido
import math
import pyaudio
import itertools
import numpy as np
# MODULES
from sineOscillator import get_sin_oscillator
from Envelope import ADSREnvelope
# CONSTANTS
BUFFER_SIZE = 256
SAMPLE_RATE = 44100
NOTE_AMP = 0.1
# ENVELOPE STUFF
envelope = ADSREnvelope()
# -- HELPER FUNCTIONS --
#def get_samples(notes_dict, num_samples=BUFFER_SIZE):
# return [
# sum([int(next(osc) * 32767) for _, osc in notes_dict.items()])
# for _ in range(num_samples)
# ]
def get_samples(notes_dict, num_samples=BUFFER_SIZE):
samples = []
for _ in range(num_samples):
sample_value = 0.0
for note_data in notes_dict.values():
osc_sample = next(note_data["osc"])
env_value = next(note_data["env"])
sample_value += osc_sample * env_value
# env class has built in "ended" attribute
if getattr(env, "ended", False):
# if ended: MARK FOR DEATH
notes_to_remove.append(note)
samples.append(int(sample_value * 32767))
# Delete note from dictionary
for note in notes_to_remove:
del notes_dict[note]
return samples
# find the midi input device
def find_midi_input_name():
for name in mido.get_input_names():
if "CASIO" in name:
return name
raise RuntimeError("MIDI device not found")
# INITIALIZION
stream = pyaudio.PyAudio().open(
rate=SAMPLE_RATE,
channels=1,
format=pyaudio.paInt16,
output=True,
frames_per_buffer=BUFFER_SIZE,
)
port_name = find_midi_input_name()
midi_input = mido.open_input(port_name)
# -- RUN THE SYNTH --
try:
print("\n\nINPUT NOTES -- RUNNING")
notes_dict = {}
while True:
if notes_dict:
# Play the notes
samples = get_samples(notes_dict)
samples = np.int16(samples).tobytes()
stream.write(samples)
for message in midi_input.iter_pending():
# NOTE OFF
if message.type == "note_off" or (message.type == "note_on" and message.velocity == 0):
if message.note in notes_dict:
notes_dict[message.note]["env"].trigger_release()
# NOTE ON
elif message.type == "note_on":
freq = 440.0 * (2 ** ((message.note - 69) / 12))
# dictionary within a dictionary :)
notes_dict[message.note] = {
"osc": get_sin_oscillator(freq=freq, amp=message.velocity / 127),
"env": ADSREnvelope()
}
except KeyboardInterrupt as err:
midi_input.close()
stream.close()
print("Stopping...")