/
midiin.go
80 lines (72 loc) · 1.69 KB
/
midiin.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
78
79
80
package midi
import (
"strings"
"time"
"github.com/schollz/miti/src/log"
"github.com/schollz/miti/src/portmidi"
)
type Event struct {
MIDI int
On bool
Instrument string
Timestamp time.Time
}
func ReadAll(finished chan bool) (events chan Event, err error) {
events = make(chan Event, 100)
err = portmidi.Initialize()
if err != nil {
return
}
go func() {
numDevices := 0
log.Debugf("found %d devices", numDevices)
done := make(chan bool)
for i := 0; i < portmidi.CountDevices(); i++ {
di := portmidi.Info(portmidi.DeviceID(i))
log.Tracef("di: %+v", di)
if strings.Contains(di.Name, "Wavetable Synth") {
log.Tracef("skipping %s", di.Name)
continue
}
if strings.Contains(di.Name, "Midi Through") {
log.Tracef("skipping %s", di.Name)
continue
}
numDevices++
if di.IsInputAvailable {
log.Tracef("%s input available", di.Name)
go func(id int, events chan Event, done chan bool) {
d := portmidi.Info(portmidi.DeviceID(id))
log.Debugf("reading from %s", d.Name)
in, err := portmidi.NewInputStream(portmidi.DeviceID(id), 1024)
if err != nil {
panic(err)
}
defer in.Close()
ch := in.Listen()
for {
select {
case event := <-ch:
if event.Data1 == 0 {
continue
}
log.Tracef("event: %+v", event)
events <- Event{int(event.Data1), event.Status == 144, d.Name, time.Now()}
case <-done:
log.Debug("closing midi read")
return
}
}
}(i, events, done)
}
}
<-finished
for i := 0; i < numDevices; i++ {
done <- true
}
time.Sleep(100 * time.Millisecond)
log.Debug("terminating")
portmidi.Terminate()
}()
return
}