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) :
49 self
._findVersesLoops
()
51 def _parseMusic(self
) :
55 for measureNode
in self
.node
.getElementsByTagName('measure') :
57 # divisions de la noire
58 divisions
= int(_getNodeValue(measureNode
, 'attributes/divisions', divisions
))
59 for noteNode
in measureNode
.getElementsByTagName('note') :
60 note
= Note(noteNode
, divisions
, previous
)
62 measureNotes
.append(note
)
66 previous
.addDuration(note
)
70 self
.notes
.extend(measureNotes
)
72 def _findChorus(self
):
73 """ le refrain correspond aux notes pour lesquelles
74 il n'existe q'une seule syllable attachée.
77 for i
, note
in enumerate(self
.notes
) :
79 if start
is None and ll
== 1 :
81 elif start
is not None and ll
> 1 :
84 self
.chorus
= self
.notes
[start
:stop
]
86 def _findVersesLoops(self
) :
87 "recherche des couplets / boucles"
88 verse
= self
.verses
[0]
89 for note
in self
.notes
[:-1] :
92 nll
= len(note
.next
.lyrics
)
95 self
.verses
.append(verse
)
96 verse
.append(self
.notes
[-1])
100 "exécution de la chanson avec l'alternance couplets / refrains"
101 for verse
in self
.verses
:
103 repeats
= len(verse
[0].lyrics
)
105 for i
in range(repeats
) :
107 print "---couplet%d---" % i
111 print "---refrain---"
112 for note
in self
.chorus
:
119 for note
, verseIndex
in self
.iterNotes() :
120 print note
, note
.lyrics
[verseIndex
]
123 def assignNotesFromMidiNoteNumbers(self
):
124 # TODO faire le mapping bande hauteur midi
125 for i
in range(len(self
.midiNoteNumbers
)):
126 noteInExtendedScale
= 0
127 while self
.midiNoteNumbers
[i
] > self
.scale
[noteInExtendedScale
] and noteInExtendedScale
< len(self
.scale
)-1:
128 noteInExtendedScale
+= 1
129 if self
.midiNoteNumbers
[i
]<self
.scale
[noteInExtendedScale
]:
130 noteInExtendedScale
-= 1
131 self
.notes
.append(noteInExtendedScale
)
134 class Barline(object) :
136 def __init__(self
, node
) :
138 self
.location
= node
.getAttribute('location')
140 repeat
= node
.getElementsByTagName('repeat')[0]
141 repeat
= {'direction' : repeat
.getAttribute('direction'),
142 'times' : int(repeat
.getAttribute('times') or 1)}
150 scale
= [55, 57, 59, 60, 62, 64, 65, 67, 69, 71, 72]
152 def __init__(self
, node
, divisions
, previous
) :
155 self
.step
= _getNodeValue(node
, 'pitch/step', None)
156 if self
.step
is not None :
157 self
.octave
= int(_getNodeValue(node
, 'pitch/octave'))
158 self
.alter
= int(_getNodeValue(node
, 'pitch/alter', 0))
159 elif self
.node
.getElementsByTagName('rest') :
162 NotImplementedError(self
.node
.toxml('utf-8'))
164 self
._duration
= float(_getNodeValue(node
, 'duration'))
166 for ly
in node
.getElementsByTagName('lyric') :
167 self
.lyrics
.append(Lyric(ly
))
169 self
.divisions
= divisions
170 self
.previous
= previous
174 return (u
'%5s %2s %2d %4s' % (self
.nom
, self
.name
, self
.midi
, round(self
.duration
, 2))).encode('utf-8')
178 def addDuration(self
, note
) :
179 self
._duration
= self
.duration
+ note
.duration
184 mid
= DIATO_SCALE
[self
.step
]
185 mid
= mid
+ (self
.octave
- OCTAVE_REF
) * 12
186 mid
= mid
+ self
.alter
191 return self
._duration
/ self
.divisions
195 name
= '%s%d' % (self
.step
, self
.octave
)
200 name
= '%s%s' % (name
, abs(self
.alter
) * alterext
)
205 name
= FR_NOTES
[self
.step
]
210 name
= '%s%s' % (name
, abs(self
.alter
) * alterext
)
215 return self
.scale
.index(self
.midi
)
218 class Lyric(object) :
220 _syllabicModifiers
= {
227 def __init__(self
, node
) :
229 self
.syllabic
= _getNodeValue(node
, 'syllabic', 'single')
230 self
.text
= _getNodeValue(node
, 'text')
233 text
= self
._syllabicModifiers
[self
.syllabic
] % self
.text
234 return text
.encode('utf-8')
240 def _getNodeValue(node
, path
, default
=_marker
) :
242 for name
in path
.split('/') :
243 node
= node
.getElementsByTagName(name
)[0]
244 return node
.firstChild
.nodeValue
246 if default
is _marker
:
251 def musicXml2Song(input, partIndex
=0, printNotes
=False) :
252 if isinstance(input, StringTypes
) :
253 input = open(input, 'r')
256 doc
= d
.documentElement
258 # TODO conversion préalable score-timewise -> score-partwise
259 assert doc
.nodeName
== u
'score-partwise'
261 parts
= doc
.getElementsByTagName('part')
262 leadPart
= parts
[partIndex
]
264 part
= Part(leadPart
)
272 # divisions de la noire
274 # midiNotes, durations, lyrics = [], [], []
276 # for measureNode in leadPart.getElementsByTagName('measure') :
277 # divisions = int(_getNodeValue(measureNode, 'attributes/divisions', divisions))
278 # for noteNode in measureNode.getElementsByTagName('note') :
279 # note = Note(noteNode, divisions)
281 # print note.name, note.midi, note.duration, note.lyric
282 # midiNotes.append(note.midi)
283 # durations.append(note.duration)
284 # lyrics.append(note.lyric)
287 # midiNoteNumbers = midiNotes,
288 # noteLengths = durations,
290 # notesInExtendedScale=None)
295 usage
= "%prog musicXmlFile.xml outputSongFile.smwi [options]"
296 op
= OptionParser(usage
)
297 op
.add_option("-i", "--part-index", dest
="partIndex"
299 , help = "Index de la partie qui contient le champ.")
300 op
.add_option("-p", '--print', dest
='printNotes'
301 , action
="store_true"
303 , help = "Affiche les notes sur la sortie standard (debug)")
305 options
, args
= op
.parse_args()
308 raise SystemExit(op
.format_help())
310 musicXml2Song(args
[0], partIndex
=options
.partIndex
, printNotes
=options
.printNotes
)
314 if __name__
== '__main__' :