Zack Scholl

zack.scholl@gmail.com

How to install portmidi

 / #software #music #golang 

A simple way to get MIDI and Golang work together using portmidi.

The Go libraries for MIDI devices - github.com/rakyll/portmidi and github.com/xlab/portmidi - both use the portmidi library with CGo. This means that building any package that requires these dependencies will need to also compile portmidi.

Here are simple instructions for macOS, Linux, and Windows to get started with portmidi and Go.

Install portmidi on Mac

Open a terminal and do

brew install portmidi

Install portmidi on Linux

Open a terminal and do:

sudo apt install libportmidi-dev

Install portmidi on Windows

First install MSYS2. This will allow you to add a natively built PortMidi directly onto your system.

Once that is installed, run MSYS2 and in the command prompt install PortMidi with the following command:

1> pacman -S mingw-w64-x86_64-portmidi

In order to get it to work, in Powershell you should add the following two environmental variables when you try to build a Go program (note, if you didn’t install MSYS2 into C:\msys64 you will need to change that directory):

1$env:CGO_CFLAGS="-IC:\msys64\mingw64\include"
2$env:CGO_LDFLAGS="-LC:\msys64\mingw64\lib"

Simply copy and paste those environmental variables into the terminal you are using before doing a go build or go run.

Test it out

To test it, run and build this program:

 1package main
 2
 3import (
 4	"fmt"
 5
 6	"github.com/rakyll/portmidi"
 7)
 8
 9func main() {
10	err := portmidi.Initialize()
11	if err != nil {
12		panic(err)
13	}
14	fmt.Println("[INFO] total MIDI devices:", portmidi.CountDevices())
15}

If everything worked correctly, you should be able to compile and run!