Search code examples
javaandroidmidi

How to send MIDI to own virtual output port with Android MIDI Package?


I am creating a Java Android app which uses the Android MIDI Package: https://developer.android.com/reference/android/media/midi/package-summary#extend_midideviceservice

The app needs to deploy its own virtual midi input and output port. So far the input side is working nicely. I can deploy the output port, its visible in other apps but I don't know how send to the output port and can't find proper documentation on that.

Does anyone have good documentation/example on opening and using the self-deployed output port?

My device_info.xml:

<devices>
    <device
        manufacturer="anyManufacturer"
        product="Virtual"
        name="myApp Virtual Inport">
        <input-port name="input" />
    </device>
    <device
        manufacturer="anyManufacturer"
        product="Virtual"
        name="myApp Virtual Outport">
        <output-port name="output" />
    </device>
</devices>

Solution

  • My own solution:

    XML:

    <devices>
        <device
            manufacturer="anyManufacturer"
            product="Virtual"
            name="myApp Virtual Port">
            <input-port name="input" />
            <output-port name="output" />
        </device>
    </devices>
    

    Then in the service call getOutputPortReceivers() to get the output port. https://developer.android.com/reference/android/media/midi/MidiDeviceService#getOutputPortReceivers()

    then you can use send() on that MidiReceiver.

    public class MIDIConnectDeviceService extends MidiDeviceService {
        private MidiReceiver mInputReceiver = new MyReceiver();
        private static MidiReceiver mOutputReceiver; 
    
        @Override
        public void onCreate() {
            super.onCreate();
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
        }
    
        @Override
        // Declare the receivers associated with your input ports.
        public MidiReceiver[] onGetInputPortReceivers() {
            return new MidiReceiver[] { mInputReceiver };
        }    
    
        public static void send(byte[] msg, int offset, int count, long timestamp) throws IOException {
            if (mOutputReceiver != null){
                mOutputReceiver.send(msg, offset, count, timestamp);
            }
        }
    
        class MyReceiver extends MidiReceiver {
            @Override
            public void onSend(byte[] data, int offset, int count,
                               long timestamp) throws IOException {
    
            }
        }
    
        @Override
        public void onDeviceStatusChanged(MidiDeviceStatus status) {
            MidiReceiver[] midiReceivers = getOutputPortReceivers();
            mOutputReceiver = midiReceivers[0];
        }
    }