eb5d5c3b86b36f73a934c88c0fd99738421ff6aa
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 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')
261 text
= self
._syllabicModifiers
[self
.syllabic
] % self
.text
262 return text
.encode('utf-8')
268 def _getNodeValue(node
, path
, default
=_marker
) :
270 for name
in path
.split('/') :
271 node
= node
.getElementsByTagName(name
)[0]
272 return node
.firstChild
.nodeValue
274 if default
is _marker
:
279 def musicXml2Song(input, partIndex
=0, printNotes
=False) :
280 if isinstance(input, StringTypes
) :
281 input = open(input, 'r')
284 doc
= d
.documentElement
286 # TODO conversion préalable score-timewise -> score-partwise
287 assert doc
.nodeName
== u
'score-partwise'
289 parts
= doc
.getElementsByTagName('part')
290 leadPart
= parts
[partIndex
]
292 part
= Part(leadPart
)
300 # divisions de la noire
302 # midiNotes, durations, lyrics = [], [], []
304 # for measureNode in leadPart.getElementsByTagName('measure') :
305 # divisions = int(_getNodeValue(measureNode, 'attributes/divisions', divisions))
306 # for noteNode in measureNode.getElementsByTagName('note') :
307 # note = Note(noteNode, divisions)
309 # print note.name, note.midi, note.duration, note.lyric
310 # midiNotes.append(note.midi)
311 # durations.append(note.duration)
312 # lyrics.append(note.lyric)
315 # midiNoteNumbers = midiNotes,
316 # noteLengths = durations,
318 # notesInExtendedScale=None)
323 usage
= "%prog musicXmlFile.xml outputSongFile.smwi [options]"
324 op
= OptionParser(usage
)
325 op
.add_option("-i", "--part-index", dest
="partIndex"
327 , help = "Index de la partie qui contient le champ.")
328 op
.add_option("-p", '--print', dest
='printNotes'
329 , action
="store_true"
331 , help = "Affiche les notes sur la sortie standard (debug)")
333 options
, args
= op
.parse_args()
336 raise SystemExit(op
.format_help())
338 musicXml2Song(args
[0], partIndex
=options
.partIndex
, printNotes
=options
.printNotes
)
342 if __name__
== '__main__' :