-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtranslate.rb
89 lines (66 loc) · 1.7 KB
/
translate.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/usr/bin/env ruby
require 'nokogiri'
exit 0 if ARGV.length < 1 || !File.exists?(ARGV[0])
file = File.open ARGV[0]
doc = Nokogiri::XML file
notes = []
durations = []
i = 0
divisions = doc.search("divisions").inner_text.to_i
sound = doc.search("sound")
if sound.first then
tempo = sound.first.attribute("tempo").to_i
else
tempo = 120
end
quarter_note = 60.0 / tempo / divisions * 1000.0
doc.search('measure').each do |measure|
measure.search('note').each do |note|
break if i > 2000
note_name = note.search("step").inner_text
note_name += "S" if note.search("alter").inner_text == "1"
note_name += note.search("octave").inner_text
note_name = "0" if note_name.length < 0
notes.push note_name.upcase
duration = note.search("duration").inner_text
if duration.length > 0 then
duration = duration.to_i * quarter_note
else
type = note.search("type").inner_text
case type
when "whole"
duration = quarter_note * 4
when "half"
duration = quarter_note * 2
when "quarter"
duration = quarter_note
when "eighth"
duration = quarter_note / 2.0
else
duration = quarter_note * 4
end
end
durations.push duration.to_s
i += 1
end
end
output = "int notes[] = {"
notes.each do |note|
output += "NOTE_" + note + ","
end
output += "};\n"
output += "int durations[] = {"
durations.each do |duration|
duration = "0" if duration.length < 1
output += duration + ","
end
output += "};\n"
output += "int melody_size = #{notes.length};\n"
out = File.open "melody.txt", "w"
out.write output
out.close
sketch = File.read "source.txt"
sketch["!!MELODY!!"] = output
out = File.open "musicxml_to_arduino.ino", "w"
out.write sketch
out.close