-
Notifications
You must be signed in to change notification settings - Fork 0
/
analyze.go
77 lines (66 loc) · 1.31 KB
/
analyze.go
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
package midi
import (
"os"
"strings"
"github.com/gomidi/midi"
"github.com/gomidi/midi/midimessage/channel"
"github.com/gomidi/midi/smf"
"github.com/gomidi/midi/smf/smfreader"
"github.com/schollz/musical-keyboard/src/utils"
)
type Phrase struct {
Filename string
// TotalNotes has the total number of notes
TotalNotes int
// IsMinor indicates a C-minor key
IsMinor bool
// RH indicates whether it is a right-handed piece
RH bool
}
func Analyze(fnames []string) (phrases []Phrase, err error) {
phrases = make([]Phrase, len(fnames))
i := 0
for _, fname := range fnames {
if strings.Contains(fname, ".tr") {
continue
}
phrases[i], err = analyze(fname)
if err != nil {
return
}
i++
}
phrases = phrases[:i]
return
}
func analyze(fname string) (p Phrase, err error) {
p.Filename = fname
f, err := os.Open(fname)
if err != nil {
return
}
defer f.Close()
rd := smfreader.New(f)
var m midi.Message
noteSum := 0.0
for {
m, err = rd.Read()
if err != nil {
break
}
switch v := m.(type) {
case channel.NoteOn:
p.TotalNotes++
log.Debug(utils.MidiToNote(v.Key()))
if strings.Contains(utils.MidiToNote(v.Key()), "Eb") {
p.IsMinor = true
}
noteSum += float64(v.Key())
}
}
p.RH = noteSum/float64(p.TotalNotes) > 60
if err == smf.ErrFinished {
err = nil
}
return
}