d7651b2704c9716dd7c237ad2e4bc5f05ec9885a
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
)
87 previous
.addDuration(note
)
88 except AttributeError :
89 # can occur if part starts with a rest.
90 if previous
is not None :
91 # something else is wrong.
96 self
.notes
.extend(measureNotes
)
98 for note
in measureNotes
:
99 if not distinctNotesDict
.has_key(note
.midi
) :
100 distinctNotesDict
[note
.midi
] = True
101 self
.distinctNotes
.append(note
)
105 barlineNode
= measureNode
.getElementsByTagName('barline')[0]
109 barline
= Barline(barlineNode
, measureNotes
)
111 self
.repeats
.append(barline
)
113 self
.distinctNotes
.sort(lambda a
, b
: cmp(a
.midi
, b
.midi
))
114 sounds
= self
.node
.getElementsByTagName('sound')
116 for sound
in sounds
:
117 if sound
.hasAttribute('tempo') :
118 tempo
= float(sound
.getAttribute('tempo'))
121 self
.quarterNoteDuration
= int(round(60000/tempo
))
125 def _findChorus(self
):
126 """ le refrain correspond aux notes pour lesquelles
127 il n'existe q'une seule syllable attachée.
130 for i
, note
in enumerate(self
.notes
) :
131 ll
= len(note
.lyrics
)
132 if start
is None and ll
== 1 :
134 elif start
is not None and ll
> 1 :
137 if not (start
or stop
) :
140 self
.chorus
= self
.notes
[start
:stop
]
142 def _findVersesLoops(self
) :
143 "recherche des couplets / boucles"
144 verse
= self
.verses
[0]
145 for note
in self
.notes
[:-1] :
147 ll
= len(note
.lyrics
)
148 nll
= len(note
.next
.lyrics
)
151 self
.verses
.append(verse
)
152 verse
.append(self
.notes
[-1])
155 def iterNotes(self
, indefinitely
=True) :
156 "exécution de la chanson avec l'alternance couplets / refrains"
157 if indefinitely
== False :
158 iterable
= self
.verses
160 iterable
= cycle(self
.verses
)
161 for verse
in iterable
:
162 #print "---partie---"
163 repeats
= len(verse
[0].lyrics
)
165 for i
in range(repeats
) :
167 #print "---couplet%d---" % i
171 #print "---refrain---"
172 for note
in self
.chorus
:
179 for note
, verseIndex
in self
.iterNotes(indefinitely
=False) :
180 print note
, note
.lyrics
[verseIndex
]
183 def assignNotesFromMidiNoteNumbers(self
):
184 # TODO faire le mapping bande hauteur midi
185 for i
in range(len(self
.midiNoteNumbers
)):
186 noteInExtendedScale
= 0
187 while self
.midiNoteNumbers
[i
] > self
.scale
[noteInExtendedScale
] and noteInExtendedScale
< len(self
.scale
)-1:
188 noteInExtendedScale
+= 1
189 if self
.midiNoteNumbers
[i
]<self
.scale
[noteInExtendedScale
]:
190 noteInExtendedScale
-= 1
191 self
.notes
.append(noteInExtendedScale
)
194 class Barline(object) :
196 def __init__(self
, node
, measureNotes
) :
198 location
= self
.location
= node
.getAttribute('location') or 'right'
200 repeatN
= node
.getElementsByTagName('repeat')[0]
201 repeat
= {'direction' : repeatN
.getAttribute('direction'),
202 'times' : int(repeatN
.getAttribute('times') or 1)}
203 if location
== 'left' :
204 repeat
['note'] = measureNotes
[0]
205 elif location
== 'right' :
206 repeat
['note'] = measureNotes
[-1]
208 raise ValueError(location
)
215 if self
.location
== 'left' :
217 elif self
.location
== 'right' :
227 def midi_to_step_alter_octave(midi
):
228 stepIndex
= midi
% 12
229 step
, alter
= CHROM_SCALE
[stepIndex
]
230 octave
= midi
/ 12 - 1
231 return step
, alter
, octave
234 def __init__(self
, *args
) :
236 self
.step
, self
.alter
, self
.octave
= args
237 elif len(args
) == 1 :
239 self
.step
, self
.alter
, self
.octave
= Tone
.midi_to_step_alter_octave(midi
)
243 mid
= DIATO_SCALE
[self
.step
]
244 mid
= mid
+ (self
.octave
- OCTAVE_REF
) * 12
245 mid
= mid
+ self
.alter
251 name
= u
'%s%d' % (self
.step
, self
.octave
)
256 name
= '%s%s' % (name
, abs(self
.alter
) * alterext
)
261 name
= FR_NOTES
[self
.step
]
266 name
= u
'%s%s' % (name
, abs(self
.alter
) * alterext
)
272 scale
= [55, 57, 59, 60, 62, 64, 65, 67, 69, 71, 72]
274 def __init__(self
, node
, divisions
, previous
) :
277 self
.tiedStart
= False
278 self
.tiedStop
= False
280 tieds
= _getElementsByPath(node
, 'notations/tied', [])
282 if tied
.getAttribute('type') == 'start' :
283 self
.tiedStart
= True
284 elif tied
.getAttribute('type') == 'stop' :
287 self
.step
= _getNodeValue(node
, 'pitch/step', None)
288 if self
.step
is not None :
289 self
.octave
= int(_getNodeValue(node
, 'pitch/octave'))
290 self
.alter
= int(_getNodeValue(node
, 'pitch/alter', 0))
291 elif self
.node
.getElementsByTagName('rest') :
294 NotImplementedError(self
.node
.toxml('utf-8'))
296 self
._duration
= float(_getNodeValue(node
, 'duration'))
298 for ly
in node
.getElementsByTagName('lyric') :
299 self
.lyrics
.append(Lyric(ly
))
301 self
.divisions
= divisions
302 self
.previous
= previous
306 return (u
'%5s %2s %2d %4s' % (self
.nom
, self
.name
, self
.midi
, round(self
.duration
, 2))).encode('utf-8')
309 return self
.name
.encode('utf-8')
311 def addDuration(self
, note
) :
312 self
._duration
= self
.duration
+ note
.duration
317 return self
._duration
/ self
.divisions
321 return self
.scale
.index(self
.midi
)
324 class Lyric(object) :
326 _syllabicModifiers
= {
329 'middle' : u
'- %s -',
333 def __init__(self
, node
) :
335 self
.syllabic
= _getNodeValue(node
, 'syllabic', 'single')
336 self
.text
= _getNodeValue(node
, 'text')
339 text
= self
._syllabicModifiers
[self
.syllabic
] % self
.text
343 return self
.syllabus().encode('utf-8')
349 def _getNodeValue(node
, path
, default
=_marker
) :
351 for name
in path
.split('/') :
352 node
= node
.getElementsByTagName(name
)[0]
353 return node
.firstChild
.nodeValue
355 if default
is _marker
:
360 def _getElementsByPath(node
, path
, default
=_marker
) :
362 parts
= path
.split('/')
363 for name
in parts
[:-1] :
364 node
= node
.getElementsByTagName(name
)[0]
365 return node
.getElementsByTagName(parts
[-1])
367 if default
is _marker
:
372 def musicXml2Song(input, partIndex
=0, autoDetectChorus
=True, printNotes
=False) :
373 if isinstance(input, StringTypes
) :
374 input = open(input, 'r')
377 doc
= d
.documentElement
379 # TODO conversion préalable score-timewise -> score-partwise
380 assert doc
.nodeName
== u
'score-partwise'
382 parts
= doc
.getElementsByTagName('part')
383 leadPart
= parts
[partIndex
]
385 part
= Part(leadPart
, autoDetectChorus
=autoDetectChorus
)
395 usage
= "%prog musicXmlFile.xml [options]"
396 op
= OptionParser(usage
)
397 op
.add_option("-i", "--part-index", dest
="partIndex"
399 , help = "Index de la partie qui contient le champ.")
401 op
.add_option("-p", '--print', dest
='printNotes'
402 , action
="store_true"
404 , help = "Affiche les notes sur la sortie standard (debug)")
406 op
.add_option("-c", '--no-chorus', dest
='autoDetectChorus'
407 , action
="store_false"
409 , help = "désactive la détection du refrain")
412 options
, args
= op
.parse_args()
415 raise SystemExit(op
.format_help())
417 musicXml2Song(args
[0],
418 partIndex
=options
.partIndex
,
419 autoDetectChorus
=options
.autoDetectChorus
,
420 printNotes
=options
.printNotes
)
423 if __name__
== '__main__' :