d24d81a673c69e4bcc7bc43688be61c6289a36ab
1 # -*- coding: utf-8 -*-
3 converstion 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
) :
112 "exécution de la chanson avec l'alternance couplets / refrains"
113 for verse
in cycle(self
.verses
) :
115 repeats
= len(verse
[0].lyrics
)
117 for i
in range(repeats
) :
119 print "---couplet%d---" % i
123 print "---refrain---"
124 for note
in self
.chorus
:
131 for note
, verseIndex
in self
.iterNotes() :
132 print note
, note
.lyrics
[verseIndex
]
135 def assignNotesFromMidiNoteNumbers(self
):
136 # TODO faire le mapping bande hauteur midi
137 for i
in range(len(self
.midiNoteNumbers
)):
138 noteInExtendedScale
= 0
139 while self
.midiNoteNumbers
[i
] > self
.scale
[noteInExtendedScale
] and noteInExtendedScale
< len(self
.scale
)-1:
140 noteInExtendedScale
+= 1
141 if self
.midiNoteNumbers
[i
]<self
.scale
[noteInExtendedScale
]:
142 noteInExtendedScale
-= 1
143 self
.notes
.append(noteInExtendedScale
)
146 class Barline(object) :
148 def __init__(self
, node
, measureNotes
) :
150 location
= self
.location
= node
.getAttribute('location') or 'right'
152 repeatN
= node
.getElementsByTagName('repeat')[0]
153 repeat
= {'direction' : repeatN
.getAttribute('direction'),
154 'times' : int(repeatN
.getAttribute('times') or 1)}
155 if location
== 'left' :
156 repeat
['note'] = measureNotes
[0]
157 elif location
== 'right' :
158 repeat
['note'] = measureNotes
[-1]
160 raise ValueError(location
)
167 if self
.location
== 'left' :
169 elif self
.location
== 'right' :
177 scale
= [55, 57, 59, 60, 62, 64, 65, 67, 69, 71, 72]
179 def __init__(self
, node
, divisions
, previous
) :
182 self
.step
= _getNodeValue(node
, 'pitch/step', None)
183 if self
.step
is not None :
184 self
.octave
= int(_getNodeValue(node
, 'pitch/octave'))
185 self
.alter
= int(_getNodeValue(node
, 'pitch/alter', 0))
186 elif self
.node
.getElementsByTagName('rest') :
189 NotImplementedError(self
.node
.toxml('utf-8'))
191 self
._duration
= float(_getNodeValue(node
, 'duration'))
193 for ly
in node
.getElementsByTagName('lyric') :
194 self
.lyrics
.append(Lyric(ly
))
196 self
.divisions
= divisions
197 self
.previous
= previous
201 return (u
'%5s %2s %2d %4s' % (self
.nom
, self
.name
, self
.midi
, round(self
.duration
, 2))).encode('utf-8')
204 return self
.name
.encode('utf-8')
206 def addDuration(self
, note
) :
207 self
._duration
= self
.duration
+ note
.duration
212 mid
= DIATO_SCALE
[self
.step
]
213 mid
= mid
+ (self
.octave
- OCTAVE_REF
) * 12
214 mid
= mid
+ self
.alter
219 return self
._duration
/ self
.divisions
223 name
= '%s%d' % (self
.step
, self
.octave
)
228 name
= '%s%s' % (name
, abs(self
.alter
) * alterext
)
233 name
= FR_NOTES
[self
.step
]
238 name
= '%s%s' % (name
, abs(self
.alter
) * alterext
)
243 return self
.scale
.index(self
.midi
)
246 class Lyric(object) :
248 _syllabicModifiers
= {
255 def __init__(self
, node
) :
257 self
.syllabic
= _getNodeValue(node
, 'syllabic', 'single')
258 self
.text
= _getNodeValue(node
, 'text')
260 def syllabus(self
, encoding
='utf-8'):
261 text
= self
._syllabicModifiers
[self
.syllabic
] % self
.text
262 return text
.encode(encoding
)
265 return self
.syllabus()
271 def _getNodeValue(node
, path
, default
=_marker
) :
273 for name
in path
.split('/') :
274 node
= node
.getElementsByTagName(name
)[0]
275 return node
.firstChild
.nodeValue
277 if default
is _marker
:
282 def musicXml2Song(input, partIndex
=0, printNotes
=False) :
283 if isinstance(input, StringTypes
) :
284 input = open(input, 'r')
287 doc
= d
.documentElement
289 # TODO conversion préalable score-timewise -> score-partwise
290 assert doc
.nodeName
== u
'score-partwise'
292 parts
= doc
.getElementsByTagName('part')
293 leadPart
= parts
[partIndex
]
295 part
= Part(leadPart
)
303 # divisions de la noire
305 # midiNotes, durations, lyrics = [], [], []
307 # for measureNode in leadPart.getElementsByTagName('measure') :
308 # divisions = int(_getNodeValue(measureNode, 'attributes/divisions', divisions))
309 # for noteNode in measureNode.getElementsByTagName('note') :
310 # note = Note(noteNode, divisions)
312 # print note.name, note.midi, note.duration, note.lyric
313 # midiNotes.append(note.midi)
314 # durations.append(note.duration)
315 # lyrics.append(note.lyric)
318 # midiNoteNumbers = midiNotes,
319 # noteLengths = durations,
321 # notesInExtendedScale=None)
326 usage
= "%prog musicXmlFile.xml outputSongFile.smwi [options]"
327 op
= OptionParser(usage
)
328 op
.add_option("-i", "--part-index", dest
="partIndex"
330 , help = "Index de la partie qui contient le champ.")
331 op
.add_option("-p", '--print', dest
='printNotes'
332 , action
="store_true"
334 , help = "Affiche les notes sur la sortie standard (debug)")
336 options
, args
= op
.parse_args()
339 raise SystemExit(op
.format_help())
341 musicXml2Song(args
[0], partIndex
=options
.partIndex
, printNotes
=options
.printNotes
)
345 if __name__
== '__main__' :