pachet commited on
Commit
a3cb78c
·
1 Parent(s): dd9364e

Added format_converstions.py

Browse files
Files changed (1) hide show
  1. format_conversions.py +34 -0
format_conversions.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from music21 import converter, musicxml
2
+ import verovio
3
+
4
+ class Format_Converter:
5
+
6
+ @classmethod
7
+ def midi_to_musicxml_string(cls, midi_path):
8
+ # Parse MIDI file into a music21 stream
9
+ score = converter.parse(midi_path)
10
+ # Export to MusicXML string
11
+ exporter = musicxml.m21ToXml.GeneralObjectExporter(score)
12
+ musicxml_str = exporter.parse().decode('utf-8') # parse() returns bytes
13
+ return musicxml_str
14
+
15
+ @classmethod
16
+ def xml_to_mei_string(cls, tk, xmlstring):
17
+ tk.loadData(xmlstring)
18
+ return tk.getMEI()
19
+
20
+ @classmethod
21
+ def midi_to_svg(cls, tk, midi_path):
22
+ try:
23
+ # Convert MIDI to MEI using music21
24
+ musicxml = cls.midi_to_musicxml_string(midi_path)
25
+ mei_str = cls.xml_to_mei_string(musicxml)
26
+ # Load MEI and render SVG
27
+ tk.loadData(mei_str)
28
+ svg = tk.renderToSVG(1)
29
+ return svg
30
+ except Exception as e:
31
+ return f"<p style='color:red'>Error: {e}</p>"
32
+
33
+ if __name__ == '__main__':
34
+ svg_string = Format_Converter().midi_to_svg(verovio.toolkit(), 'output.mid')