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
= []
56 self
.quarterNoteDuration
= 500
60 self
.songStartsWithChorus
= False
61 self
._findVersesLoops
(autoDetectChorus
)
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
)
86 previous
.addDuration(note
)
87 except AttributeError :
88 # can occur if part starts with a rest.
89 if previous
is not None :
90 # something else is wrong.
95 self
.notes
.extend(measureNotes
)
97 for note
in measureNotes
:
98 if not distinctNotesDict
.has_key(note
.midi
) :
99 distinctNotesDict
[note
.midi
] = True
100 self
.distinctNotes
.append(note
)
104 barlineNode
= measureNode
.getElementsByTagName('barline')[0]
108 barline
= Barline(barlineNode
, measureNotes
)
110 self
.repeats
.append(barline
)
112 self
.distinctNotes
.sort(lambda a
, b
: cmp(a
.midi
, b
.midi
))
113 sounds
= self
.node
.getElementsByTagName('sound')
115 for sound
in sounds
:
116 if sound
.hasAttribute('tempo') :
117 tempo
= float(sound
.getAttribute('tempo'))
120 self
.quarterNoteDuration
= int(round(60000/tempo
))
123 def _findVersesLoops(self
, autoDetectChorus
) :
124 "recherche des couplets / boucles"
125 verse
= self
.verses
[0]
126 for note
in self
.notes
[:-1] :
128 ll
= len(note
.lyrics
)
129 nll
= len(note
.next
.lyrics
)
132 self
.verses
.append(verse
)
133 verse
.append(self
.notes
[-1])
135 if autoDetectChorus
and len(self
.verses
) > 1 :
136 for i
, verse
in enumerate(self
.verses
) :
137 if len(verse
[0].lyrics
) == 1 :
138 self
.chorus
= self
.verses
.pop(i
)
139 self
.songStartsWithChorus
= i
==0
143 def iterNotes(self
, indefinitely
=True) :
144 "exécution de la chanson avec l'alternance couplets / refrains"
145 if indefinitely
== False :
146 iterable
= self
.verses
148 iterable
= cycle(self
.verses
)
149 for verse
in iterable
:
150 if self
.songStartsWithChorus
:
151 for note
in self
.chorus
:
154 #print "---partie---"
155 repeats
= len(verse
[0].lyrics
)
157 for i
in range(repeats
) :
159 #print "---couplet%d---" % i
163 #print "---refrain---"
164 for note
in self
.chorus
:
171 for note
, verseIndex
in self
.iterNotes(indefinitely
=False) :
172 print note
, note
.lyrics
[verseIndex
]
175 def assignNotesFromMidiNoteNumbers(self
):
176 # TODO faire le mapping bande hauteur midi
177 for i
in range(len(self
.midiNoteNumbers
)):
178 noteInExtendedScale
= 0
179 while self
.midiNoteNumbers
[i
] > self
.scale
[noteInExtendedScale
] and noteInExtendedScale
< len(self
.scale
)-1:
180 noteInExtendedScale
+= 1
181 if self
.midiNoteNumbers
[i
]<self
.scale
[noteInExtendedScale
]:
182 noteInExtendedScale
-= 1
183 self
.notes
.append(noteInExtendedScale
)
186 class Barline(object) :
188 def __init__(self
, node
, measureNotes
) :
190 location
= self
.location
= node
.getAttribute('location') or 'right'
192 repeatN
= node
.getElementsByTagName('repeat')[0]
193 repeat
= {'direction' : repeatN
.getAttribute('direction'),
194 'times' : int(repeatN
.getAttribute('times') or 1)}
195 if location
== 'left' :
196 repeat
['note'] = measureNotes
[0]
197 elif location
== 'right' :
198 repeat
['note'] = measureNotes
[-1]
200 raise ValueError(location
)
207 if self
.location
== 'left' :
209 elif self
.location
== 'right' :
219 def midi_to_step_alter_octave(midi
):
220 stepIndex
= midi
% 12
221 step
, alter
= CHROM_SCALE
[stepIndex
]
222 octave
= midi
/ 12 - 1
223 return step
, alter
, octave
226 def __init__(self
, *args
) :
228 self
.step
, self
.alter
, self
.octave
= args
229 elif len(args
) == 1 :
231 self
.step
, self
.alter
, self
.octave
= Tone
.midi_to_step_alter_octave(midi
)
235 mid
= DIATO_SCALE
[self
.step
]
236 mid
= mid
+ (self
.octave
- OCTAVE_REF
) * 12
237 mid
= mid
+ self
.alter
243 name
= u
'%s%d' % (self
.step
, self
.octave
)
248 name
= '%s%s' % (name
, abs(self
.alter
) * alterext
)
253 name
= FR_NOTES
[self
.step
]
258 name
= u
'%s%s' % (name
, abs(self
.alter
) * alterext
)
264 scale
= [55, 57, 59, 60, 62, 64, 65, 67, 69, 71, 72]
266 def __init__(self
, node
, divisions
, previous
) :
269 self
.tiedStart
= False
270 self
.tiedStop
= False
272 tieds
= _getElementsByPath(node
, 'notations/tied', [])
274 if tied
.getAttribute('type') == 'start' :
275 self
.tiedStart
= True
276 elif tied
.getAttribute('type') == 'stop' :
279 self
.step
= _getNodeValue(node
, 'pitch/step', None)
280 if self
.step
is not None :
281 self
.octave
= int(_getNodeValue(node
, 'pitch/octave'))
282 self
.alter
= int(_getNodeValue(node
, 'pitch/alter', 0))
283 elif self
.node
.getElementsByTagName('rest') :
286 NotImplementedError(self
.node
.toxml('utf-8'))
288 self
._duration
= float(_getNodeValue(node
, 'duration'))
290 for ly
in node
.getElementsByTagName('lyric') :
291 self
.lyrics
.append(Lyric(ly
))
293 self
.divisions
= divisions
294 self
.previous
= previous
298 return (u
'%5s %2s %2d %4s' % (self
.nom
, self
.name
, self
.midi
, round(self
.duration
, 2))).encode('utf-8')
301 return self
.name
.encode('utf-8')
303 def addDuration(self
, note
) :
304 self
._duration
= self
.duration
+ note
.duration
309 return self
._duration
/ self
.divisions
313 return self
.scale
.index(self
.midi
)
316 class Lyric(object) :
318 _syllabicModifiers
= {
321 'middle' : u
'- %s -',
325 def __init__(self
, node
) :
327 self
.syllabic
= _getNodeValue(node
, 'syllabic', 'single')
328 self
.text
= _getNodeValue(node
, 'text')
331 text
= self
._syllabicModifiers
[self
.syllabic
] % self
.text
335 return self
.syllabus().encode('utf-8')
341 def _getNodeValue(node
, path
, default
=_marker
) :
343 for name
in path
.split('/') :
344 node
= node
.getElementsByTagName(name
)[0]
345 return node
.firstChild
.nodeValue
347 if default
is _marker
:
352 def _getElementsByPath(node
, path
, default
=_marker
) :
354 parts
= path
.split('/')
355 for name
in parts
[:-1] :
356 node
= node
.getElementsByTagName(name
)[0]
357 return node
.getElementsByTagName(parts
[-1])
359 if default
is _marker
:
364 def musicXml2Song(input, partIndex
=0, autoDetectChorus
=True, printNotes
=False) :
365 if isinstance(input, StringTypes
) :
366 input = open(input, 'r')
369 doc
= d
.documentElement
371 # TODO conversion préalable score-timewise -> score-partwise
372 assert doc
.nodeName
== u
'score-partwise'
374 parts
= doc
.getElementsByTagName('part')
375 leadPart
= parts
[partIndex
]
377 part
= Part(leadPart
, autoDetectChorus
=autoDetectChorus
)
387 usage
= "%prog musicXmlFile.xml [options]"
388 op
= OptionParser(usage
)
389 op
.add_option("-i", "--part-index", dest
="partIndex"
391 , help = "Index de la partie qui contient le champ.")
393 op
.add_option("-p", '--print', dest
='printNotes'
394 , action
="store_true"
396 , help = "Affiche les notes sur la sortie standard (debug)")
398 op
.add_option("-c", '--no-chorus', dest
='autoDetectChorus'
399 , action
="store_false"
401 , help = "désactive la détection du refrain")
404 options
, args
= op
.parse_args()
407 raise SystemExit(op
.format_help())
409 musicXml2Song(args
[0],
410 partIndex
=options
.partIndex
,
411 autoDetectChorus
=options
.autoDetectChorus
,
412 printNotes
=options
.printNotes
)
415 if __name__
== '__main__' :