-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmidi_synth.py
More file actions
executable file
·81 lines (66 loc) · 1.94 KB
/
Copy pathmidi_synth.py
File metadata and controls
executable file
·81 lines (66 loc) · 1.94 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
#!/usr/bin/env python3
# Monophonic Python MIDI synthesizer
import pyaudio
import mido
import struct, math, time
# sleep time in main loop
SLEEP = 0.01
# audio buffer size (determines latency)
# Increase this if there is crackling audio output.
BSIZE = 256
# sample rate
ARATE = 44100
################################################################################
last_note = -1
xpos = 0
freq = 0
amp = 0
amp_loss = 0
# callback function for audio data
def callback(in_data, frame_count, time_info, status):
global xpos, amp
data = b""
delt = 2 * math.pi / ARATE * freq
for i in range(frame_count):
if freq > 0:
v = math.sin(xpos) + 0.5 * math.sin(2 * xpos) + 0.25 * math.sin(4 * xpos)
b = struct.pack("h", round(18000 * amp * v))
xpos += delt
amp *= amp_loss
else:
b = struct.pack("h", 0)
data += b
return data, pyaudio.paContinue
inport = mido.open_input()
paud = pyaudio.PyAudio()
stream = paud.open(
format=paud.get_format_from_width(2),
channels=1,
rate=ARATE,
output=True,
frames_per_buffer=BSIZE,
stream_callback=callback,
)
print("latency [s] = %.5f" % stream.get_output_latency())
while True:
for msg in inport.iter_pending():
if msg.type == "note_on" and msg.velocity > 0:
freq = 440 * 2 ** ((msg.note - 69) / 12)
last_note = msg.note
xpos = 0
amp = 1
a_min, a_max, a_sel = math.log(21), math.log(108), math.log(msg.note)
lossfac = 50000 - 49000 * ((a_sel - a_min) / (a_max - a_min))
lossfac *= ARATE / 44100
amp_loss = 1 - 1 / lossfac
if msg.type == "note_off" or (msg.type == "note_on" and msg.velocity == 0):
if msg.note == last_note:
freq = 0
last_note = -1
try:
time.sleep(SLEEP)
except:
break
stream.close()
paud.terminate()
inport.close()