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
)
77 measureNotes
.append(note
)
81 previous
.addDuration(note
)
85 self
.notes
.extend(measureNotes
)
87 for note
in measureNotes
:
88 if not distinctNotesDict
.has_key(note
.midi
) :
89 distinctNotesDict
[note
.midi
] = True
90 self
.distinctNotes
.append(note
)
94 barlineNode
= measureNode
.getElementsByTagName('barline')[0]
98 barline
= Barline(barlineNode
, measureNotes
)
100 self
.repeats
.append(barline
)
102 self
.distinctNotes
.sort(lambda a
, b
: cmp(a
.midi
, b
.midi
))
105 def _findChorus(self
):
106 """ le refrain correspond aux notes pour lesquelles
107 il n'existe q'une seule syllable attachée.
110 for i
, note
in enumerate(self
.notes
) :
111 ll
= len(note
.lyrics
)
112 if start
is None and ll
== 1 :
114 elif start
is not None and ll
> 1 :
117 self
.chorus
= self
.notes
[start
:stop
]
119 def _findVersesLoops(self
) :
120 "recherche des couplets / boucles"
121 verse
= self
.verses
[0]
122 for note
in self
.notes
[:-1] :
124 ll
= len(note
.lyrics
)
125 nll
= len(note
.next
.lyrics
)
128 self
.verses
.append(verse
)
129 verse
.append(self
.notes
[-1])
132 def iterNotes(self
, indefinitely
=True) :
133 "exécution de la chanson avec l'alternance couplets / refrains"
134 print 'indefinitely', indefinitely
135 if indefinitely
== False :
136 iterable
= self
.verses
138 iterable
= cycle(self
.verses
)
139 for verse
in iterable
:
141 repeats
= len(verse
[0].lyrics
)
143 for i
in range(repeats
) :
145 print "---couplet%d---" % i
149 print "---refrain---"
150 for note
in self
.chorus
:
157 for note
, verseIndex
in self
.iterNotes(indefinitely
=False) :
158 print note
, note
.lyrics
[verseIndex
]
161 def assignNotesFromMidiNoteNumbers(self
):
162 # TODO faire le mapping bande hauteur midi
163 for i
in range(len(self
.midiNoteNumbers
)):
164 noteInExtendedScale
= 0
165 while self
.midiNoteNumbers
[i
] > self
.scale
[noteInExtendedScale
] and noteInExtendedScale
< len(self
.scale
)-1:
166 noteInExtendedScale
+= 1
167 if self
.midiNoteNumbers
[i
]<self
.scale
[noteInExtendedScale
]:
168 noteInExtendedScale
-= 1
169 self
.notes
.append(noteInExtendedScale
)
172 class Barline(object) :
174 def __init__(self
, node
, measureNotes
) :
176 location
= self
.location
= node
.getAttribute('location') or 'right'
178 repeatN
= node
.getElementsByTagName('repeat')[0]
179 repeat
= {'direction' : repeatN
.getAttribute('direction'),
180 'times' : int(repeatN
.getAttribute('times') or 1)}
181 if location
== 'left' :
182 repeat
['note'] = measureNotes
[0]
183 elif location
== 'right' :
184 repeat
['note'] = measureNotes
[-1]
186 raise ValueError(location
)
193 if self
.location
== 'left' :
195 elif self
.location
== 'right' :
205 def midi_to_step_alter_octave(midi
):
206 stepIndex
= midi
% 12
207 step
, alter
= CHROM_SCALE
[stepIndex
]
208 octave
= midi
/ 12 - 1
209 return step
, alter
, octave
212 def __init__(self
, *args
) :
214 self
.step
, self
.alter
, self
.octave
= args
215 elif len(args
) == 1 :
217 self
.step
, self
.alter
, self
.octave
= Tone
.midi_to_step_alter_octave(midi
)
221 mid
= DIATO_SCALE
[self
.step
]
222 mid
= mid
+ (self
.octave
- OCTAVE_REF
) * 12
223 mid
= mid
+ self
.alter
229 name
= '%s%d' % (self
.step
, self
.octave
)
234 name
= '%s%s' % (name
, abs(self
.alter
) * alterext
)
239 name
= FR_NOTES
[self
.step
]
244 name
= '%s%s' % (name
, abs(self
.alter
) * alterext
)
250 scale
= [55, 57, 59, 60, 62, 64, 65, 67, 69, 71, 72]
252 def __init__(self
, node
, divisions
, previous
) :
255 self
.step
= _getNodeValue(node
, 'pitch/step', None)
256 if self
.step
is not None :
257 self
.octave
= int(_getNodeValue(node
, 'pitch/octave'))
258 self
.alter
= int(_getNodeValue(node
, 'pitch/alter', 0))
259 elif self
.node
.getElementsByTagName('rest') :
262 NotImplementedError(self
.node
.toxml('utf-8'))
264 self
._duration
= float(_getNodeValue(node
, 'duration'))
266 for ly
in node
.getElementsByTagName('lyric') :
267 self
.lyrics
.append(Lyric(ly
))
269 self
.divisions
= divisions
270 self
.previous
= previous
274 return (u
'%5s %2s %2d %4s' % (self
.nom
, self
.name
, self
.midi
, round(self
.duration
, 2))).encode('utf-8')
277 return self
.name
.encode('utf-8')
279 def addDuration(self
, note
) :
280 self
._duration
= self
.duration
+ note
.duration
285 return self
._duration
/ self
.divisions
289 return self
.scale
.index(self
.midi
)
292 class Lyric(object) :
294 _syllabicModifiers
= {
301 def __init__(self
, node
) :
303 self
.syllabic
= _getNodeValue(node
, 'syllabic', 'single')
304 self
.text
= _getNodeValue(node
, 'text')
306 def syllabus(self
, encoding
='utf-8'):
307 text
= self
._syllabicModifiers
[self
.syllabic
] % self
.text
308 return text
.encode(encoding
)
311 return self
.syllabus()
317 def _getNodeValue(node
, path
, default
=_marker
) :
319 for name
in path
.split('/') :
320 node
= node
.getElementsByTagName(name
)[0]
321 return node
.firstChild
.nodeValue
323 if default
is _marker
:
328 def musicXml2Song(input, partIndex
=0, printNotes
=False) :
329 if isinstance(input, StringTypes
) :
330 input = open(input, 'r')
333 doc
= d
.documentElement
335 # TODO conversion préalable score-timewise -> score-partwise
336 assert doc
.nodeName
== u
'score-partwise'
338 parts
= doc
.getElementsByTagName('part')
339 leadPart
= parts
[partIndex
]
341 part
= Part(leadPart
)
351 usage
= "%prog musicXmlFile.xml [options]"
352 op
= OptionParser(usage
)
353 op
.add_option("-i", "--part-index", dest
="partIndex"
355 , help = "Index de la partie qui contient le champ.")
356 op
.add_option("-p", '--print', dest
='printNotes'
357 , action
="store_true"
359 , help = "Affiche les notes sur la sortie standard (debug)")
361 options
, args
= op
.parse_args()
364 raise SystemExit(op
.format_help())
366 musicXml2Song(args
[0], partIndex
=options
.partIndex
, printNotes
=options
.printNotes
)
370 if __name__
== '__main__' :