Android MIDI User Guide
This document describes how to use the Android MIDI API in Java.
The Android MIDI package allows users to:
The API is “transport agnostic”. But there are several transports currently supported:
A Device is a MIDI capable object that has zero or more InputPorts and OutputPorts.
An InputPort has 16 channels and can receive MIDI messages from an OutputPort or an app.
An OutputPort has 16 channels and can send MIDI messages to an InputPort or an app.
MidiService is a centralized process that keeps track of all devices and brokers communication between them.
MidiManager is a class that the application or a device manager calls to communicate with the MidiService.
The primary class for accessing the MIDI package is through the MidiManager.
MidiManager m = (MidiManager)context.getSystemService(Context.MIDI_SERVICE);
When an app starts, it can get a list of all the available MIDI devices. This information can be presented to a user, allowing them to choose a device.
MidiDeviceInfo[] infos = m.getDeviceList();
The application can request notification when, for example, keyboards are plugged in or unplugged.
m.registerDeviceCallback(new MidiManager.DeviceCallback() { public void onDeviceAdded( MidiDeviceInfo info ) { ... } public void onDeviceRemoved( MidiDeviceInfo info ) { ... } });
You can query the number of input and output ports.
int numInputs = info.getInputPortCount(); int numOutputs = info.getOutputPortCount();
Note that “input” and “output” are from the standpoint of the device. So a synthesizer will have an “input” port that receives messages. A keyboard will have an “output” port that sends messages.
The MidiDeviceInfo has a bundle of properties.
Bundle properties = info.getProperties(); String manufacturer = properties .getString(MidiDeviceInfo.PROPERTY_MANUFACTURER);
Other properties include PROPERTY_PRODUCT, PROPERTY_NAME, PROPERTY_SERIAL_NUMBER
You can get the names of the ports from a PortInfo object.
PortInfo portInfo = info.getInputPortInfo(i); String portName = portInfo.getName();
To access a MIDI device you need to open it first. The open is asynchronous so you need to provide a callback for completion. You can specify an optional Handler if you want the callback to occur on a specific Thread.
m.openDevice(info, new MidiManager.DeviceOpenCallback() { @Override public void onDeviceOpened(MidiDeviceInfo deviceInfo, MidiDevice device) { if (device == null) { Log.e(TAG, "could not open " + deviceInfo); } else { ... }, new Handler(Looper.getMainLooper()) );
If you want to send a message to a MIDI Device then you need to open an “input” port with exclusive access.
MidiInputPort inputPort = device.openInputPort(index);
MIDI messages are sent as byte arrays. Here we encode a NoteOn message.
byte[] buffer = new buffer[64]; int numBytes = 0; buffer[numBytes++] = 0x90 + channel; // note on buffer[numBytes++] = pitch; buffer[numBytes++] = velocity; int offset = 0; // post is non-blocking inputPort.send(buffer, offset, numBytes);
Sometimes it is convenient to send MIDI messages with a timestamp. By scheduling events in the future we can mask scheduling jitter. Android MIDI timestamps are based on the monotonic nanosecond system timer. This is consistent with the other audio and input timers.
Here we send a message with a timestamp 2 seconds in the future.
long now = System.nanoTime(); long future = now + (2 * 1000000000); inputPort.sendWithTimestamp(buffer, offset, numBytes, future);
If you want to cancel events that you have scheduled in the future then call flush().
inputPort.flush(); // discard events
If there were any MIDI NoteOff message left in the buffer then they will be discarded and you may get stuck notes. So we recommend sending “all notes off” after doing a flush.
To receive MIDI data from a device you need to extend MidiReceiver. Then connect your receiver to an output port of the device.
class MyReceiver extends MidiReceiver { public void onReceive(byte[] data, int offset, int count, long timestamp) throws IOException { // parse MIDI or whatever } } MidiOutputPort outputPort = device.openOutputPort(index); outputPort.connect(new MyReceiver());
The data that arrives is not validated or aligned in any particular way. It is raw MIDI data and can contain multiple messages or partial messages. It might contain System Real-Time messages, which can be interleaved inside other messages. Some applications have their own MIDI parsers so pre-parsing the data would be redundant. If an application wants the data parsed and aligned then they can use the MidiFramer utility.
An app can provide a MIDI Service that can be used by other apps. For example, an app can provide a custom synthesizer that other apps can send messages to.
An app declares that it will function as a MIDI server in the AndroidManifest.xml file.
<service android:name="MySynthDeviceService"> <intent-filter> <action android:name="android.media.midi.MidiDeviceService" /> </intent-filter> <meta-data android:name="android.media.midi.MidiDeviceService" android:resource="@xml/synth_device_info" /> </service>
The details of the resource in this example is stored in “res/xml/synth_device_info.xml”.
<devices> <device manufacturer="MyCompany" product="MidiSynthBasic"> <input-port name="input" /> </device> </devices>
You then define your server by extending android.media.midi.MidiDeviceService. Let’s assume you have a MySynthEngine class that extends MidiReceiver.
import android.media.midi.MidiDeviceService; import android.media.midi.MidiDeviceStatus; import android.media.midi.MidiReceiver; public class MidiSynthDeviceService extends MidiDeviceService { private static final String TAG = "MidiSynthDeviceService"; private MySynthEngine mSynthEngine = new MySynthEngine(); @Override public void onCreate() { super.onCreate(); } @Override public void onDestroy() { mSynthEngine.stop(); super.onDestroy(); } @Override // Declare the receivers associated with your input ports. public MidiReceiver[] onGetInputPortReceivers() { return new MidiReceiver[] { mSynthEngine }; } /** * This will get called when clients connect or disconnect. * You can use it to turn on your synth only when needed. */ @Override public void onDeviceStatusChanged(MidiDeviceStatus status) { if (status.isInputPortOpen(0)) { mSynthEngine.start(); } else { mSynthEngine.stop(); } } }