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 FR_NOTES
= {'C' : u
'Do',
37 requiresExtendedScale
= False
38 scale
= [55, 57, 59, 60, 62, 64, 65, 67, 69, 71, 72]
39 quarterNoteLength
= 400
41 def __init__(self
, node
, autoDetectChorus
=True) :
50 self
._findVersesLoops
()
52 def _parseMusic(self
) :
56 for measureNode
in self
.node
.getElementsByTagName('measure') :
59 # iteration sur les notes
60 # divisions de la noire
61 divisions
= int(_getNodeValue(measureNode
, 'attributes/divisions', divisions
))
62 for noteNode
in measureNode
.getElementsByTagName('note') :
63 note
= Note(noteNode
, divisions
, previous
)
65 measureNotes
.append(note
)
69 previous
.addDuration(note
)
72 self
.notes
.extend(measureNotes
)
76 barlineNode
= measureNode
.getElementsByTagName('barline')[0]
80 barline
= Barline(barlineNode
, measureNotes
)
82 self
.repeats
.append(barline
)
84 def _findChorus(self
):
85 """ le refrain correspond aux notes pour lesquelles
86 il n'existe q'une seule syllable attachée.
89 for i
, note
in enumerate(self
.notes
) :
91 if start
is None and ll
== 1 :
93 elif start
is not None and ll
> 1 :
96 self
.chorus
= self
.notes
[start
:stop
]
98 def _findVersesLoops(self
) :
99 "recherche des couplets / boucles"
100 verse
= self
.verses
[0]
101 for note
in self
.notes
[:-1] :
103 ll
= len(note
.lyrics
)
104 nll
= len(note
.next
.lyrics
)
107 self
.verses
.append(verse
)
108 verse
.append(self
.notes
[-1])
111 def iterNotes(self
, indefinitely
=True) :
112 "exécution de la chanson avec l'alternance couplets / refrains"
113 print 'indefinitely', indefinitely
114 if indefinitely
== False :
115 iterable
= self
.verses
117 iterable
= cycle(self
.verses
)
118 for verse
in iterable
:
120 repeats
= len(verse
[0].lyrics
)
122 for i
in range(repeats
) :
124 print "---couplet%d---" % i
128 print "---refrain---"
129 for note
in self
.chorus
:
136 for note
, verseIndex
in self
.iterNotes(indefinitely
=False) :
137 print note
, note
.lyrics
[verseIndex
]
140 def assignNotesFromMidiNoteNumbers(self
):
141 # TODO faire le mapping bande hauteur midi
142 for i
in range(len(self
.midiNoteNumbers
)):
143 noteInExtendedScale
= 0
144 while self
.midiNoteNumbers
[i
] > self
.scale
[noteInExtendedScale
] and noteInExtendedScale
< len(self
.scale
)-1:
145 noteInExtendedScale
+= 1
146 if self
.midiNoteNumbers
[i
]<self
.scale
[noteInExtendedScale
]:
147 noteInExtendedScale
-= 1
148 self
.notes
.append(noteInExtendedScale
)
151 class Barline(object) :
153 def __init__(self
, node
, measureNotes
) :
155 location
= self
.location
= node
.getAttribute('location') or 'right'
157 repeatN
= node
.getElementsByTagName('repeat')[0]
158 repeat
= {'direction' : repeatN
.getAttribute('direction'),
159 'times' : int(repeatN
.getAttribute('times') or 1)}
160 if location
== 'left' :
161 repeat
['note'] = measureNotes
[0]
162 elif location
== 'right' :
163 repeat
['note'] = measureNotes
[-1]
165 raise ValueError(location
)
172 if self
.location
== 'left' :
174 elif self
.location
== 'right' :
182 scale
= [55, 57, 59, 60, 62, 64, 65, 67, 69, 71, 72]
184 def __init__(self
, node
, divisions
, previous
) :
187 self
.step
= _getNodeValue(node
, 'pitch/step', None)
188 if self
.step
is not None :
189 self
.octave
= int(_getNodeValue(node
, 'pitch/octave'))
190 self
.alter
= int(_getNodeValue(node
, 'pitch/alter', 0))
191 elif self
.node
.getElementsByTagName('rest') :
194 NotImplementedError(self
.node
.toxml('utf-8'))
196 self
._duration
= float(_getNodeValue(node
, 'duration'))
198 for ly
in node
.getElementsByTagName('lyric') :
199 self
.lyrics
.append(Lyric(ly
))
201 self
.divisions
= divisions
202 self
.previous
= previous
206 return (u
'%5s %2s %2d %4s' % (self
.nom
, self
.name
, self
.midi
, round(self
.duration
, 2))).encode('utf-8')
209 return self
.name
.encode('utf-8')
211 def addDuration(self
, note
) :
212 self
._duration
= self
.duration
+ note
.duration
217 mid
= DIATO_SCALE
[self
.step
]
218 mid
= mid
+ (self
.octave
- OCTAVE_REF
) * 12
219 mid
= mid
+ self
.alter
224 return self
._duration
/ self
.divisions
228 name
= '%s%d' % (self
.step
, self
.octave
)
233 name
= '%s%s' % (name
, abs(self
.alter
) * alterext
)
238 name
= FR_NOTES
[self
.step
]
243 name
= '%s%s' % (name
, abs(self
.alter
) * alterext
)
248 return self
.scale
.index(self
.midi
)
251 class Lyric(object) :
253 _syllabicModifiers
= {
260 def __init__(self
, node
) :
262 self
.syllabic
= _getNodeValue(node
, 'syllabic', 'single')
263 self
.text
= _getNodeValue(node
, 'text')
265 def syllabus(self
, encoding
='utf-8'):
266 text
= self
._syllabicModifiers
[self
.syllabic
] % self
.text
267 return text
.encode(encoding
)
270 return self
.syllabus()
276 def _getNodeValue(node
, path
, default
=_marker
) :
278 for name
in path
.split('/') :
279 node
= node
.getElementsByTagName(name
)[0]
280 return node
.firstChild
.nodeValue
282 if default
is _marker
:
287 def musicXml2Song(input, partIndex
=0, printNotes
=False) :
288 if isinstance(input, StringTypes
) :
289 input = open(input, 'r')
292 doc
= d
.documentElement
294 # TODO conversion préalable score-timewise -> score-partwise
295 assert doc
.nodeName
== u
'score-partwise'
297 parts
= doc
.getElementsByTagName('part')
298 leadPart
= parts
[partIndex
]
300 part
= Part(leadPart
)
309 usage
= "%prog musicXmlFile.xml [options]"
310 op
= OptionParser(usage
)
311 op
.add_option("-i", "--part-index", dest
="partIndex"
313 , help = "Index de la partie qui contient le champ.")
314 op
.add_option("-p", '--print', dest
='printNotes'
315 , action
="store_true"
317 , help = "Affiche les notes sur la sortie standard (debug)")
319 options
, args
= op
.parse_args()
322 raise SystemExit(op
.format_help())
324 musicXml2Song(args
[0], partIndex
=options
.partIndex
, printNotes
=options
.printNotes
)
328 if __name__
== '__main__' :