-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeyboard.py
232 lines (189 loc) · 8.06 KB
/
keyboard.py
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
from os import listdir
from os.path import isfile, join
from util import *
import numpy as np
import matplotlib.pyplot as plt
import platform
if '3.5' in platform.python_version():
import fmp
if '3.6' in platform.python_version():
import fmp36 as fmp;
# FMP is a library from class 21M.387 (Professor Egozy) to compute a chromagram
class Keyboard():
def __init__(self, num_notes=20, starting_pitch=60, audio_dirpath=None, max_sound_length_sec=4, sample_rate=22050):
self.starting_pitch = starting_pitch
self.num_notes = num_notes
self.state = [0]*self.num_notes
self.audio = dict()
self.max_sound_length_sec = max_sound_length_sec
self.sample_rate = sample_rate
if audio_dirpath:
self.load_audio_files(audio_dirpath)
else:
self.load_audio_files()
# if we notice we have the same chunk of audio as previously computed, return
# the saved chromagram to speed up simulation.
self.audio_cached_chroma = {}
# precompute the chroma of certain pitches, so we don't have to do on-the-fly
self.pitch_to_chroma_energy = {}
self.compute_chroma_energies()
def possible_next_states(self):
new_states = []
for i, active in enumerate(self.state):
possible = self.state[:]
possible[i] = 1 if possible[i] == 0 else 0
new_states.append(possible)
return new_states
def toggle_note(self, pitch):
if self.in_key_range(pitch):
idx = pitch - self.starting_pitch
self.state[idx] = 1 if self.state[idx] == 0 else 0
def in_key_range(self, pitch):
above = (pitch >= self.starting_pitch)
below = (pitch < self.starting_pitch + self.num_notes)
return above and below
def load_audio_files(self, path="piano/resources/keys_wav"):
max_num_samples = self.max_sound_length_sec * self.sample_rate
files = set(get_directory_files(path, file_ext="wav"))
for pitch in range(self.starting_pitch, self.starting_pitch+self.num_notes):
file = join(path, str(pitch)+".wav")
if file in files:
wav_data = load_wav(file)
sound_start_idx = int(np.min(np.where(wav_data>0.01)[0]))
trimmed_sound = wav_data[sound_start_idx:]
if max_num_samples > trimmed_sound.shape[0]:
self.audio[pitch] = np.concatenate([trimmed_sound, np.zeros(max_num_samples - trimmed_sound.shape[0])])
else:
self.audio[pitch] = trimmed_sound[:max_num_samples]
def play_current_state(self):
sound = self.get_state_audio()
play_wav_data(sound)
def play_pitch(self, pitch):
if self.in_key_range(pitch):
play_wav_data(self.audio[pitch])
else:
print("Pitch {} not in range".format(pitch))
def get_state_audio(self, state=None):
if state is None:
state = self.state
data_len = len(list(self.audio.values())[0])
sound = np.zeros(data_len)
for i, active in enumerate(state):
if active:
sound += self.audio[self.starting_pitch+i]
return sound
def get_state_chroma(self, state=None):
if state is None:
state = self.state
sound = self.get_state_audio(state)
return self.get_audio_chroma(sound)
def get_state_chroma_energy(self, state=None, norm=True, efficient=True):
if state is None:
state = self.state
# The efficient method simply sums the energies from notes individually, instead
# of rendering them to an audio file and computing the chroma that way.
#
#
# the "efficient" method is less "accurate" to what actually synthesizing
# the notes would produce, but is pretty close. Differences are numerical
# computing errors and a few other specific things to how chromagrams are created
# but these two methods are theoretically the same:
# F(x + y) = F(x) + F(y) for fourier transform F and signals x and y
# accumulate the pre-computed energies for each note
if efficient:
# 12 musical notes in a chromagram
num_chroma_bins = 12
energy = np.zeros(num_chroma_bins)
for i, active in enumerate(state):
if active:
energy += self.pitch_to_chroma_energy[i + self.starting_pitch]
# synthesize the audio, get the chromagram, and then compute the energies
else:
energy = np.sum(self.get_state_chroma(state), axis=1)
if norm:
energy /= (np.linalg.norm(energy) + 1e-5)
return energy
def get_audio_chroma(self, sound):
window_length = 4096
hop_size = window_length//2
log_comp = 1.0
normalize = True
sound_bit = tuple(sound[:min(5000, int(len(sound)*0.2))])
# check if we have it in our cache
if sound_bit in self.audio_cached_chroma:
return self.audio_cached_chroma[sound_bit]
else:
chroma = fmp.make_chromagram(sound,
self.sample_rate,
window_length,
hop_size,
gamma=log_comp,
normalize=normalize)
# otherwise cache the chroma
self.audio_cached_chroma[sound_bit] = chroma
return chroma
def plot_state_chroma(self, state=None):
if state is None:
state = self.state
plt.title("Pitches: {}".format([x+self.starting_pitch for x in np.where(np.array(self.state) == 1)[0]]))
plt.imshow(self.get_state_chroma(state), origin='lower', aspect='auto')
plt.xlabel("Time (downsampled)")
plt.ylabel("Musical Pitch")
plt.show()
def plot_audio_chroma(self, audio):
plt.title("Audio Chromagram")
plt.imshow(self.get_audio_chroma(audio), origin='lower', aspect='auto')
plt.xlabel("Time (downsampled)")
plt.ylabel("Musical Pitch")
plt.show()
def plot_pitch(self, pitch):
if self.in_key_range(pitch):
data = self.audio[pitch]
plt.title("pitch: {}".format(str(pitch)))
plt.plot(np.arange(len(data)), data)
plt.show()
else:
print("Pitch {} not in range".format(pitch))
def score(self, song_audio, state=None):
if state is None:
state = self.state
state_vec = self.get_state_chroma_energy(state, norm=False)
song_vec = np.sum(self.get_audio_chroma(song_audio), axis=1)
# subtract the mean energy
state_vec -= np.mean(state_vec)
song_vec -= np.mean(song_vec)
song_vec /= (np.linalg.norm(song_vec) + 1e-5)
state_vec /= (np.linalg.norm(state_vec) + 1e-5)
return np.dot(state_vec, song_vec)
def compute_chroma_energies(self):
for i in range(self.num_notes):
pitch = i + self.starting_pitch
state = [0] * self.num_notes
state[i] = 1
energy = np.sum(self.get_state_chroma(state), axis=1)
energy /= np.linalg.norm(energy)
self.pitch_to_chroma_energy[pitch] = energy
def softmax(self, x, scale=10.0):
"""Compute softmax values for each sets of scores in x."""
x = np.array(x)
e_x = np.exp(x*scale)
return e_x / e_x.sum()
if __name__ == '__main__':
k = Keyboard()
k.toggle_note(60)
k.toggle_note(64)
k.toggle_note(67)
# audio = load_wav("resources/keys_wav/60.wav")
# s = k.score(audio)
# print(s)
# print(np.exp(s))
# k.play_current_state()
k.plot_state_chroma()
audio = load_wav("piano/resources/tests/test3.wav")
# # audio = load_wav("piano/resources/keys_wav/73.wav")
k.plot_audio_chroma(audio)
# for t in range(k.starting_pitch, k.starting_pitch + k.num_notes):
# k.toggle_note(t)
# res = k.score(audio)
# print(res, t)
# k.toggle_note(t)