ab6dbf9309e44a33b388feb726d527fc7f69d1fa
1 # -*- coding: utf-8 -*-
3 conversion d'un fichier musicxml en objet song minwii.
9 from types
import StringTypes
10 from xml
.dom
.minidom
import parse
11 from optparse
import OptionParser
12 from itertools
import cycle
13 #from Song import Song
17 DIATO_SCALE
= {'C' : 60,
25 CHROM_SCALE
= { 0 : ('C', 0),
39 FR_NOTES
= {'C' : u
'Do',
51 def __init__(self
, node
, autoDetectChorus
=True) :
55 self
.distinctNotes
= []
61 self
._findVersesLoops
()
63 def _parseMusic(self
) :
66 distinctNotesDict
= {}
68 for measureNode
in self
.node
.getElementsByTagName('measure') :
71 # iteration sur les notes
72 # divisions de la noire
73 divisions
= int(_getNodeValue(measureNode
, 'attributes/divisions', divisions
))
74 for noteNode
in measureNode
.getElementsByTagName('note') :
75 note
= Note(noteNode
, divisions
, previous
)
76 if (not note
.isRest
) and (not note
.tiedStop
) :
77 measureNotes
.append(note
)
81 assert previous
.tiedStart
82 previous
.addDuration(note
)
85 previous
.addDuration(note
)
89 self
.notes
.extend(measureNotes
)
91 for note
in measureNotes
:
92 if not distinctNotesDict
.has_key(note
.midi
) :
93 distinctNotesDict
[note
.midi
] = True
94 self
.distinctNotes
.append(note
)
98 barlineNode
= measureNode
.getElementsByTagName('barline')[0]
102 barline
= Barline(barlineNode
, measureNotes
)
104 self
.repeats
.append(barline
)
106 self
.distinctNotes
.sort(lambda a
, b
: cmp(a
.midi
, b
.midi
))
109 def _findChorus(self
):
110 """ le refrain correspond aux notes pour lesquelles
111 il n'existe q'une seule syllable attachée.
114 for i
, note
in enumerate(self
.notes
) :
115 ll
= len(note
.lyrics
)
116 if start
is None and ll
== 1 :
118 elif start
is not None and ll
> 1 :
121 if not (start
or stop
) :
124 self
.chorus
= self
.notes
[start
:stop
]
126 def _findVersesLoops(self
) :
127 "recherche des couplets / boucles"
128 verse
= self
.verses
[0]
129 for note
in self
.notes
[:-1] :
131 ll
= len(note
.lyrics
)
132 nll
= len(note
.next
.lyrics
)
135 self
.verses
.append(verse
)
136 verse
.append(self
.notes
[-1])
139 def iterNotes(self
, indefinitely
=True) :
140 "exécution de la chanson avec l'alternance couplets / refrains"
141 print 'indefinitely', indefinitely
142 if indefinitely
== False :
143 iterable
= self
.verses
145 iterable
= cycle(self
.verses
)
146 for verse
in iterable
:
148 repeats
= len(verse
[0].lyrics
)
150 for i
in range(repeats
) :
152 print "---couplet%d---" % i
156 print "---refrain---"
157 for note
in self
.chorus
:
164 for note
, verseIndex
in self
.iterNotes(indefinitely
=False) :
165 print note
, note
.lyrics
[verseIndex
]
168 def assignNotesFromMidiNoteNumbers(self
):
169 # TODO faire le mapping bande hauteur midi
170 for i
in range(len(self
.midiNoteNumbers
)):
171 noteInExtendedScale
= 0
172 while self
.midiNoteNumbers
[i
] > self
.scale
[noteInExtendedScale
] and noteInExtendedScale
< len(self
.scale
)-1:
173 noteInExtendedScale
+= 1
174 if self
.midiNoteNumbers
[i
]<self
.scale
[noteInExtendedScale
]:
175 noteInExtendedScale
-= 1
176 self
.notes
.append(noteInExtendedScale
)
179 class Barline(object) :
181 def __init__(self
, node
, measureNotes
) :
183 location
= self
.location
= node
.getAttribute('location') or 'right'
185 repeatN
= node
.getElementsByTagName('repeat')[0]
186 repeat
= {'direction' : repeatN
.getAttribute('direction'),
187 'times' : int(repeatN
.getAttribute('times') or 1)}
188 if location
== 'left' :
189 repeat
['note'] = measureNotes
[0]
190 elif location
== 'right' :
191 repeat
['note'] = measureNotes
[-1]
193 raise ValueError(location
)
200 if self
.location
== 'left' :
202 elif self
.location
== 'right' :
212 def midi_to_step_alter_octave(midi
):
213 stepIndex
= midi
% 12
214 step
, alter
= CHROM_SCALE
[stepIndex
]
215 octave
= midi
/ 12 - 1
216 return step
, alter
, octave
219 def __init__(self
, *args
) :
221 self
.step
, self
.alter
, self
.octave
= args
222 elif len(args
) == 1 :
224 self
.step
, self
.alter
, self
.octave
= Tone
.midi_to_step_alter_octave(midi
)
228 mid
= DIATO_SCALE
[self
.step
]
229 mid
= mid
+ (self
.octave
- OCTAVE_REF
) * 12
230 mid
= mid
+ self
.alter
236 name
= '%s%d' % (self
.step
, self
.octave
)
241 name
= '%s%s' % (name
, abs(self
.alter
) * alterext
)
246 name
= FR_NOTES
[self
.step
]
251 name
= '%s%s' % (name
, abs(self
.alter
) * alterext
)
257 scale
= [55, 57, 59, 60, 62, 64, 65, 67, 69, 71, 72]
259 def __init__(self
, node
, divisions
, previous
) :
262 self
.tiedStart
= False
263 self
.tiedStop
= False
265 tieds
= _getElementsByPath(node
, 'notations/tied', [])
267 if tied
.getAttribute('type') == 'start' :
268 self
.tiedStart
= True
269 elif tied
.getAttribute('type') == 'stop' :
272 self
.step
= _getNodeValue(node
, 'pitch/step', None)
273 if self
.step
is not None :
274 self
.octave
= int(_getNodeValue(node
, 'pitch/octave'))
275 self
.alter
= int(_getNodeValue(node
, 'pitch/alter', 0))
276 elif self
.node
.getElementsByTagName('rest') :
279 NotImplementedError(self
.node
.toxml('utf-8'))
281 self
._duration
= float(_getNodeValue(node
, 'duration'))
283 for ly
in node
.getElementsByTagName('lyric') :
284 self
.lyrics
.append(Lyric(ly
))
286 self
.divisions
= divisions
287 self
.previous
= previous
291 return (u
'%5s %2s %2d %4s' % (self
.nom
, self
.name
, self
.midi
, round(self
.duration
, 2))).encode('utf-8')
294 return self
.name
.encode('utf-8')
296 def addDuration(self
, note
) :
297 self
._duration
= self
.duration
+ note
.duration
302 return self
._duration
/ self
.divisions
306 return self
.scale
.index(self
.midi
)
309 class Lyric(object) :
311 _syllabicModifiers
= {
314 'middle' : u
'- %s -',
318 def __init__(self
, node
) :
320 self
.syllabic
= _getNodeValue(node
, 'syllabic', 'single')
321 self
.text
= _getNodeValue(node
, 'text')
324 text
= self
._syllabicModifiers
[self
.syllabic
] % self
.text
328 return self
.syllabus().encode('utf-8')
334 def _getNodeValue(node
, path
, default
=_marker
) :
336 for name
in path
.split('/') :
337 node
= node
.getElementsByTagName(name
)[0]
338 return node
.firstChild
.nodeValue
340 if default
is _marker
:
345 def _getElementsByPath(node
, path
, default
=_marker
) :
347 parts
= path
.split('/')
348 for name
in parts
[:-1] :
349 node
= node
.getElementsByTagName(name
)[0]
350 return node
.getElementsByTagName(parts
[-1])
352 if default
is _marker
:
357 def musicXml2Song(input, partIndex
=0, autoDetectChorus
=True, printNotes
=False) :
358 if isinstance(input, StringTypes
) :
359 input = open(input, 'r')
362 doc
= d
.documentElement
364 # TODO conversion préalable score-timewise -> score-partwise
365 assert doc
.nodeName
== u
'score-partwise'
367 parts
= doc
.getElementsByTagName('part')
368 leadPart
= parts
[partIndex
]
370 part
= Part(leadPart
, autoDetectChorus
=autoDetectChorus
)
380 usage
= "%prog musicXmlFile.xml [options]"
381 op
= OptionParser(usage
)
382 op
.add_option("-i", "--part-index", dest
="partIndex"
384 , help = "Index de la partie qui contient le champ.")
386 op
.add_option("-p", '--print', dest
='printNotes'
387 , action
="store_true"
389 , help = "Affiche les notes sur la sortie standard (debug)")
391 op
.add_option("-c", '--no-chorus', dest
='autoDetectChorus'
392 , action
="store_false"
394 , help = "désactive la détection du refrain")
397 options
, args
= op
.parse_args()
400 raise SystemExit(op
.format_help())
402 musicXml2Song(args
[0],
403 partIndex
=options
.partIndex
,
404 autoDetectChorus
=options
.autoDetectChorus
,
405 printNotes
=options
.printNotes
)
408 if __name__
== '__main__' :