-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
82 lines (68 loc) · 1.89 KB
/
main.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
81
82
package main
import (
"encoding/json"
"flag"
"fmt"
"github.com/rakyll/portmidi"
"os"
"os/signal"
"time"
)
type MIDINote struct {
Note int64 `json:"note"`
Velocity int64 `json:"velocity"`
Duration int64 `json:"duration"`
}
type MIDIEvent struct {
Status int64
Note MIDINote
}
func playNote(note MIDINote, noteChannel chan<- MIDIEvent) {
noteChannel <- MIDIEvent{0x90, note}
time.Sleep(time.Duration(note.Duration) * time.Millisecond)
noteChannel <- MIDIEvent{0x80, note}
}
func playSequence(notes []MIDINote, timeBetweenNotes time.Duration, noteChannel chan<- MIDIEvent) {
for {
for _, note := range notes {
go playNote(note, noteChannel)
time.Sleep(timeBetweenNotes)
}
}
}
func main() {
notesJson := flag.String("notes", "[]", `JSON array of objects with keys "note" (int), "velocity" (int), and "duration" (int). Duration value represents milliseconds.`)
interval := flag.Int("interval", 100, "Number of milliseconds between notes.")
flag.Parse()
fmt.Println("Starting sequence. Press Ctrl+C to quit...")
portmidi.Initialize()
defer portmidi.Terminate()
out, err := portmidi.NewOutputStream(portmidi.DefaultOutputDeviceID(), 1024, 0)
if err != nil {
panic(err.Error())
}
noteChannel := make(chan MIDIEvent)
notes := []MIDINote{}
err = json.Unmarshal([]byte(*notesJson), ¬es)
if err != nil {
panic(err.Error())
}
go playSequence(notes, time.Duration(*interval)*time.Millisecond, noteChannel)
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, os.Interrupt)
LOOP:
for {
select {
case event := <-noteChannel:
out.WriteShort(event.Status, event.Note.Note, event.Note.Velocity)
case <-sigint:
break LOOP
}
}
// send off for every note in the sequence. There's an "all notes off" MIDI message
// but it wasn't working on the only MIDI synth that I have.
for _, note := range notes {
out.WriteShort(0x80, note.Note, note.Velocity)
}
out.Close()
}