-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtextsongnator.py
382 lines (320 loc) · 11 KB
/
textsongnator.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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
from enum import Enum
from pyknon.genmidi import Midi
from pyknon.music import Note, NoteSeq
import os
# não usados por enquanto:
# from pyknon.notation import *
# from pyknon.pc_sets import *
# from pyknon.pcset import *
# from pyknon.simplemusic import *
class instrumentSymbol(Enum):
PIANO = 0
ACOUSTICGUITAR = 24
ELECTRICGUITAR = 27
VIOLIN = 40
VOICE = 52
APPLAUSE = 126
class musicSymbol(Enum):
A = 0
a = 1
B = 2
b = 3
C = 4
c = 5
D = 6
d = 7
E = 8
F = 9
f = 10
G = 11
g = 12
PAUSE = 13
VOLUP = 14
VOLDOWN = 15
REPEATNOTE = 16
OCTAVEUP = 17
OCTAVEDOWN = 18
RESET = 19
INSTRUMENT = 20
BPMUP = 21
BPMDOWN = 22
KEEP = 23
mapping = {
"A": musicSymbol.A,
"a": musicSymbol.A,
"A#": musicSymbol.a,
"a#": musicSymbol.a,
"B": musicSymbol.B,
"b": musicSymbol.B,
"B#": musicSymbol.b,
"b#": musicSymbol.b,
"C": musicSymbol.C,
"c": musicSymbol.C,
"C#": musicSymbol.c,
"c#": musicSymbol.c,
"D": musicSymbol.D,
"d": musicSymbol.D,
"D#": musicSymbol.d,
"d#": musicSymbol.d,
"E": musicSymbol.E,
"e": musicSymbol.E,
"F": musicSymbol.F,
"f": musicSymbol.F,
"F#": musicSymbol.f,
"f#": musicSymbol.f,
"G": musicSymbol.G,
"g": musicSymbol.G,
"G#": musicSymbol.g,
"g#": musicSymbol.g,
"+": musicSymbol.VOLUP,
"-": musicSymbol.VOLDOWN,
"O": musicSymbol.REPEATNOTE,
"o": musicSymbol.REPEATNOTE,
"I": musicSymbol.REPEATNOTE,
"i": musicSymbol.REPEATNOTE,
"U": musicSymbol.REPEATNOTE,
"u": musicSymbol.REPEATNOTE,
"O+": musicSymbol.OCTAVEUP,
"O-": musicSymbol.OCTAVEDOWN,
"?": musicSymbol.RESET,
".": musicSymbol.RESET,
"\n": musicSymbol.INSTRUMENT,
"B+": musicSymbol.BPMUP,
"B-": musicSymbol.BPMDOWN,
" ": musicSymbol.PAUSE
}
class musicSymbolDecoder:
def __init__(self):
self.__currentCharacter = ""
self.__symbols = []
def __readChar(self):
try:
self.__symbols.append(mapping[self.__currentCharacter])
# Coloca um KEEP por caractere no currentCharacter
# para lidar com O#, C+ e similares da maneira certa
except KeyError as e:
print("INFO: ", e, " não tem no dicionario, interpretando como KEEP.")
#pylint: disable=unused-variable
for char in self.__currentCharacter:
self.__symbols.append(musicSymbol.KEEP)
self.__currentCharacter = ''
def clear(self):
self.__currentCharacter = ""
self.__symbols = []
def head(self):
if self.__symbols == []:
return None
else:
return self.__symbols.pop(0)
# Prefixos:
# {O,B} de {O,B}{-,+}
# {A-G} de {A-G}#
def decode(self, char):
# Lida com os caracteres que são prefixos de outros
# que foram adicionados ao currentCharacter
if self.__currentCharacter != '':
if char in ('+', '-', '#'):
self.__currentCharacter += char
self.__readChar()
return
else:
self.__readChar()
# Lida com os caracteres que são prefixos de outros
# que recém foram lidos
if char.upper() in ('A', 'B', 'C', 'D', 'F', 'G', 'O'):
self.__currentCharacter = char
# Lida com qualquer outro caractere
else:
self.__currentCharacter = char
self.__readChar()
# Classe para guardar partes da
# música que tem um mesmo instrumento.
class Track:
def __init__(self, notes, instrument):
self.__notes = notes
self.__instrument = instrument
def getInstrument(self):
return self.__instrument
def getNotes(self):
return self.__notes
# Inserts silence into beggining (to append to some other track)
def addPause(self, note):
firstNote = self.__notes[0]
n = Note("A")
n.octave = firstNote.octave
n.volume = 0
n.dur = firstNote.dur
self.__notes.append(note)
class Player:
def __init__(self, instrument = instrumentSymbol.PIANO, volume = 100, octave = 5, beat = 150):
# notes e instrument são variáveis de "buffer" para criar Tracks e adicioná-las ao tracks
self.__notes = []
self.__instrument = instrument
self.__tracks = []
self.__instrumentIter = iter(instrumentSymbol)
next(self.__instrumentIter) # o primeiro next é o primeiro instrumento
self.__volume = volume
self.__octave = octave
self.__beat = beat
self.__decoder = musicSymbolDecoder()
def addNote(self, note):
self.__notes.append(note)
def setVolume(self, vol):
if vol >= 0:
self.__volume = vol
def getVolume(self):
return self.__volume
def incVolume(self):
self.setVolume(self.getVolume() + 1)
return self.getVolume()
def decVolume(self):
self.setVolume(self.getVolume() - 1)
return self.getVolume()
def repeatNote(self):
if self.__notes != []:
self.__notes.append(self.__notes[-1])
def __addTrack(self):
self.__tracks.append(Track(self.__notes, self.__instrument))
self.__notes = []
def setInstrument(self, instrument):
if self.__instrument != instrument:
self.__addTrack()
self.__instrument = instrument
def getInstrument(self):
return self.__instrument
def incInstrument(self):
nextInstrument = next(self.__instrumentIter)
self.setInstrument(nextInstrument)
def setOctave(self, oct):
self.__octave = oct
def getOctave(self):
return self.__octave
def incOctave(self):
self.setOctave(self.getOctave() + 1)
return self.getOctave()
def decOctave(self):
self.setOctave(self.getOctave() - 1)
return self.getOctave()
def resetOctave(self):
self.__octave = 1
def setBeat(self, bpm):
if bpm > 0:
self.__beat = bpm
def getBeat(self):
return self.__beat
def incBeat(self):
self.setBeat(self.getBeat() + 5)
return self.getBeat()
def decBeat(self):
self.setBeat(self.getBeat() - 5)
return self.getBeat()
def resetVolume(self):
self.__volume = 1
def clear(self):
self.__init__()
def addPause(self):
vol = self.getVolume()
self.setVolume(0)
self.addNote(self.symbol2Note(musicSymbol.A))
self.setVolume(vol)
def keep(self):
if self.__notes != []:
self.__notes[-1].dur += (60/self.getBeat())/4
def symbol2Note(self, symbol):
if(symbol.name.islower()):
n = Note(symbol.name.upper()+'#')
else:
n = Note(symbol.name)
n.octave = self.getOctave()
n.volume = self.getVolume()
# 60 bpm faz uma batida por segundo, e uma batida é uma semínima (0.25)
n.dur = (60/self.getBeat())/4
return n
def readSymbol(self, symbol):
# print("DEBUG: vai ler o simbolo ", symbol)
if symbol in (musicSymbol.A,
musicSymbol.a,
musicSymbol.B,
musicSymbol.b,
musicSymbol.C,
musicSymbol.c,
musicSymbol.D,
musicSymbol.d,
musicSymbol.E,
musicSymbol.F,
musicSymbol.f,
musicSymbol.G,
musicSymbol.g):
self.addNote(self.symbol2Note(symbol))
elif symbol == musicSymbol.PAUSE:
self.addPause()
elif symbol == musicSymbol.VOLUP:
self.incVolume()
elif symbol == musicSymbol.VOLDOWN:
self.decVolume()
elif symbol == musicSymbol.REPEATNOTE:
self.repeatNote()
elif symbol == musicSymbol.OCTAVEUP:
self.incOctave()
elif symbol == musicSymbol.OCTAVEDOWN:
self.decOctave()
elif symbol == musicSymbol.RESET:
self.resetOctave()
self.resetVolume()
elif symbol == musicSymbol.INSTRUMENT:
self.incInstrument()
elif symbol == musicSymbol.BPMUP:
self.incBeat()
elif symbol == musicSymbol.BPMDOWN:
self.decBeat()
elif symbol == musicSymbol.KEEP:
self.keep()
def saveSong(self, filename):
def nameFile(filename, iterator):
return "".join(filename.split(".")[:-1]) + str(iterator) + "." + filename.split(".")[-1]
if self.__notes != []:
self.__addTrack()
# for track in self.__tracks:
# track.addPause()
fileNameIterator = 0
for track in self.__tracks:
midi = Midi(number_tracks=1, instrument=track.getInstrument().value)
notes = NoteSeq(track.getNotes())
midi.seq_notes(notes, track=0)
midi.write(nameFile(filename, fileNameIterator))
fileNameIterator += 1
fileNameIterator -= 1
if fileNameIterator > 0:
for i in range(fileNameIterator):
os.system("python midisox.py --combine concatenate " +
nameFile(filename, i) + " " +
nameFile(filename, i+1) + " " +
nameFile(filename, i+1))
os.remove(nameFile(filename, i))
if os.path.exists(filename):
os.remove(filename)
os.rename(nameFile(filename, fileNameIterator), filename)
def readSheetString(self, sheet):
# Função interna para ler os dados devolvidos pelo decoder
def readDecoderHead():
symbol = self.__decoder.head()
while symbol != None:
self.readSymbol(symbol)
symbol = self.__decoder.head()
for char in sheet:
self.__decoder.decode(char)
readDecoderHead()
# Captura o último caractere, o que é preciso
# caso ele seja um de prefixo como O
self.__decoder.decode(" ")
readDecoderHead()
def generateSong(self, sheet):
self.readSheetString(sheet)
# Esta parte do código só é executada se este arquivo
# for executado, não caso seja importado como um módulo.
if __name__ == "__main__":
play = Player()
play.setInstrument(instrumentSymbol.PIANO)
play.generateSong("B+B+B+B+EEE\nCEGO-\nGO+CO-GE\nABA#A\nGO+EGA\nFGECDO-B")
play.saveSong("out.mid")
# os.system(".\\out.mid")