Skip to content

Instantly share code, notes, and snippets.

@jszwedko
Created June 3, 2016 03:47
Show Gist options
  • Save jszwedko/e53e7eebf4d12bfc1b8376efe0f28922 to your computer and use it in GitHub Desktop.
Save jszwedko/e53e7eebf4d12bfc1b8376efe0f28922 to your computer and use it in GitHub Desktop.
bf-to-midi because why not
package main
import (
"bufio"
"fmt"
"io"
"os"
"time"
"github.com/rakyll/portmidi"
)
var runeToNote = map[rune]int64{
'>': 60,
'<': 62,
'+': 64,
'-': 65,
'.': 67,
',': 69,
'[': 71,
']': 72,
}
const (
minVelocity = int64(50)
maxVelocity = int64(75)
)
func main() {
portmidi.Initialize()
defer portmidi.Terminate()
s, err := portmidi.NewOutputStream(portmidi.DeviceID(3), 1024, 0)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer s.Close()
var previousRune rune
velocity := minVelocity
reader := bufio.NewReader(os.Stdin)
for {
currentRune, _, err := reader.ReadRune()
if err != nil {
if err == io.EOF {
os.Exit(0)
}
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("%c", currentRune)
if currentRune == previousRune && velocity < maxVelocity {
velocity++
continue
}
note, ok := runeToNote[previousRune]
if ok {
err = s.WriteShort(0x90, note, velocity) // Turn on note on channel 1
if err != nil {
fmt.Println(err)
os.Exit(1)
}
time.Sleep(100 * time.Millisecond)
err = s.WriteShort(0x80, note, 0) // Turn off note on channel 1
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
previousRune = currentRune
velocity = minVelocity
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment