ec3be4a1a6ef78b793b2ac958042945c727fda88
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
62 self
._findVersesLoops
()
64 def _parseMusic(self
) :
67 distinctNotesDict
= {}
69 for measureNode
in self
.node
.getElementsByTagName('measure') :
72 # iteration sur les notes
73 # divisions de la noire
74 divisions
= int(_getNodeValue(measureNode
, 'attributes/divisions', divisions
))
75 for noteNode
in measureNode
.getElementsByTagName('note') :
76 note
= Note(noteNode
, divisions
, previous
)
77 if (not note
.isRest
) and (not note
.tiedStop
) :
78 measureNotes
.append(note
)
82 assert previous
.tiedStart
83 previous
.addDuration(note
)
86 previous
.addDuration(note
)
90 self
.notes
.extend(measureNotes
)
92 for note
in measureNotes
:
93 if not distinctNotesDict
.has_key(note
.midi
) :
94 distinctNotesDict
[note
.midi
] = True
95 self
.distinctNotes
.append(note
)
99 barlineNode
= measureNode
.getElementsByTagName('barline')[0]
103 barline
= Barline(barlineNode
, measureNotes
)
105 self
.repeats
.append(barline
)
107 self
.distinctNotes
.sort(lambda a
, b
: cmp(a
.midi
, b
.midi
))
108 sounds
= self
.node
.getElementsByTagName('sound')
110 for sound
in sounds
:
111 if sound
.hasAttribute('tempo') :
112 tempo
= float(sound
.getAttribute('tempo'))
115 self
.quarterNoteDuration
= int(round(60000/tempo
))
119 def _findChorus(self
):
120 """ le refrain correspond aux notes pour lesquelles
121 il n'existe q'une seule syllable attachée.
124 for i
, note
in enumerate(self
.notes
) :
125 ll
= len(note
.lyrics
)
126 if start
is None and ll
== 1 :
128 elif start
is not None and ll
> 1 :
131 if not (start
or stop
) :
134 self
.chorus
= self
.notes
[start
:stop
]
136 def _findVersesLoops(self
) :
137 "recherche des couplets / boucles"
138 verse
= self
.verses
[0]
139 for note
in self
.notes
[:-1] :
141 ll
= len(note
.lyrics
)
142 nll
= len(note
.next
.lyrics
)
145 self
.verses
.append(verse
)
146 verse
.append(self
.notes
[-1])
149 def iterNotes(self
, indefinitely
=True) :
150 "exécution de la chanson avec l'alternance couplets / refrains"
151 if indefinitely
== False :
152 iterable
= self
.verses
154 iterable
= cycle(self
.verses
)
155 for verse
in iterable
:
157 repeats
= len(verse
[0].lyrics
)
159 for i
in range(repeats
) :
161 print "---couplet%d---" % i
165 print "---refrain---"
166 for note
in self
.chorus
:
173 for note
, verseIndex
in self
.iterNotes(indefinitely
=False) :
174 print note
, note
.lyrics
[verseIndex
]
177 def assignNotesFromMidiNoteNumbers(self
):
178 # TODO faire le mapping bande hauteur midi
179 for i
in range(len(self
.midiNoteNumbers
)):
180 noteInExtendedScale
= 0
181 while self
.midiNoteNumbers
[i
] > self
.scale
[noteInExtendedScale
] and noteInExtendedScale
< len(self
.scale
)-1:
182 noteInExtendedScale
+= 1
183 if self
.midiNoteNumbers
[i
]<self
.scale
[noteInExtendedScale
]:
184 noteInExtendedScale
-= 1
185 self
.notes
.append(noteInExtendedScale
)
188 class Barline(object) :
190 def __init__(self
, node
, measureNotes
) :
192 location
= self
.location
= node
.getAttribute('location') or 'right'
194 repeatN
= node
.getElementsByTagName('repeat')[0]
195 repeat
= {'direction' : repeatN
.getAttribute('direction'),
196 'times' : int(repeatN
.getAttribute('times') or 1)}
197 if location
== 'left' :
198 repeat
['note'] = measureNotes
[0]
199 elif location
== 'right' :
200 repeat
['note'] = measureNotes
[-1]
202 raise ValueError(location
)
209 if self
.location
== 'left' :
211 elif self
.location
== 'right' :
221 def midi_to_step_alter_octave(midi
):
222 stepIndex
= midi
% 12
223 step
, alter
= CHROM_SCALE
[stepIndex
]
224 octave
= midi
/ 12 - 1
225 return step
, alter
, octave
228 def __init__(self
, *args
) :
230 self
.step
, self
.alter
, self
.octave
= args
231 elif len(args
) == 1 :
233 self
.step
, self
.alter
, self
.octave
= Tone
.midi_to_step_alter_octave(midi
)
237 mid
= DIATO_SCALE
[self
.step
]
238 mid
= mid
+ (self
.octave
- OCTAVE_REF
) * 12
239 mid
= mid
+ self
.alter
245 name
= '%s%d' % (self
.step
, self
.octave
)
250 name
= '%s%s' % (name
, abs(self
.alter
) * alterext
)
255 name
= FR_NOTES
[self
.step
]
260 name
= u
'%s%s' % (name
, abs(self
.alter
) * alterext
)
266 scale
= [55, 57, 59, 60, 62, 64, 65, 67, 69, 71, 72]
268 def __init__(self
, node
, divisions
, previous
) :
271 self
.tiedStart
= False
272 self
.tiedStop
= False
274 tieds
= _getElementsByPath(node
, 'notations/tied', [])
276 if tied
.getAttribute('type') == 'start' :
277 self
.tiedStart
= True
278 elif tied
.getAttribute('type') == 'stop' :
281 self
.step
= _getNodeValue(node
, 'pitch/step', None)
282 if self
.step
is not None :
283 self
.octave
= int(_getNodeValue(node
, 'pitch/octave'))
284 self
.alter
= int(_getNodeValue(node
, 'pitch/alter', 0))
285 elif self
.node
.getElementsByTagName('rest') :
288 NotImplementedError(self
.node
.toxml('utf-8'))
290 self
._duration
= float(_getNodeValue(node
, 'duration'))
292 for ly
in node
.getElementsByTagName('lyric') :
293 self
.lyrics
.append(Lyric(ly
))
295 self
.divisions
= divisions
296 self
.previous
= previous
300 return (u
'%5s %2s %2d %4s' % (self
.nom
, self
.name
, self
.midi
, round(self
.duration
, 2))).encode('utf-8')
303 return self
.name
.encode('utf-8')
305 def addDuration(self
, note
) :
306 self
._duration
= self
.duration
+ note
.duration
311 return self
._duration
/ self
.divisions
315 return self
.scale
.index(self
.midi
)
318 class Lyric(object) :
320 _syllabicModifiers
= {
323 'middle' : u
'- %s -',
327 def __init__(self
, node
) :
329 self
.syllabic
= _getNodeValue(node
, 'syllabic', 'single')
330 self
.text
= _getNodeValue(node
, 'text')
333 text
= self
._syllabicModifiers
[self
.syllabic
] % self
.text
337 return self
.syllabus().encode('utf-8')
343 def _getNodeValue(node
, path
, default
=_marker
) :
345 for name
in path
.split('/') :
346 node
= node
.getElementsByTagName(name
)[0]
347 return node
.firstChild
.nodeValue
349 if default
is _marker
:
354 def _getElementsByPath(node
, path
, default
=_marker
) :
356 parts
= path
.split('/')
357 for name
in parts
[:-1] :
358 node
= node
.getElementsByTagName(name
)[0]
359 return node
.getElementsByTagName(parts
[-1])
361 if default
is _marker
:
366 def musicXml2Song(input, partIndex
=0, autoDetectChorus
=True, printNotes
=False) :
367 if isinstance(input, StringTypes
) :
368 input = open(input, 'r')
371 doc
= d
.documentElement
373 # TODO conversion préalable score-timewise -> score-partwise
374 assert doc
.nodeName
== u
'score-partwise'
376 parts
= doc
.getElementsByTagName('part')
377 leadPart
= parts
[partIndex
]
379 part
= Part(leadPart
, autoDetectChorus
=autoDetectChorus
)
389 usage
= "%prog musicXmlFile.xml [options]"
390 op
= OptionParser(usage
)
391 op
.add_option("-i", "--part-index", dest
="partIndex"
393 , help = "Index de la partie qui contient le champ.")
395 op
.add_option("-p", '--print', dest
='printNotes'
396 , action
="store_true"
398 , help = "Affiche les notes sur la sortie standard (debug)")
400 op
.add_option("-c", '--no-chorus', dest
='autoDetectChorus'
401 , action
="store_false"
403 , help = "désactive la détection du refrain")
406 options
, args
= op
.parse_args()
409 raise SystemExit(op
.format_help())
411 musicXml2Song(args
[0],
412 partIndex
=options
.partIndex
,
413 autoDetectChorus
=options
.autoDetectChorus
,
414 printNotes
=options
.printNotes
)
417 if __name__
== '__main__' :