Olivier Rivard
Olivier Rivard

Reputation: 216

Sending and receiving Java Midi Sysex message

I would like to send and receive SysEx message with Java Sound API.

I am able to send message to the device but I want to receive the SysEx message sent from the devices after the command is sent.

Here is my code:

 try {
            MidiDevice device = MidiSystem.getMidiDevice(info);

            byte[] dataAlone = {
                    (byte) 0xF0,
            (byte) 0xB0, (byte) 0x63, (byte) 0x00,
            (byte) 0xB0, (byte) 0x62, (byte) 0x0C,
            (byte) 0xB0, (byte) 0x60, (byte) 0x7F,
            (byte) 0xF7
            };
            SysexMessage message1 = new SysexMessage(dataAlone, dataAlone.length);

            device.open();
            Receiver rcvr = device.getReceiver();

            rcvr.send(message1, -1);

            rcvr.close();
        } catch (InvalidMidiDataException | MidiUnavailableException e) {
            System.out.println(e);
        }

When I send this message, the device is answering back with SysEx message that I can see on midi application running on my computer.

Upvotes: 1

Views: 579

Answers (1)

jjazzboss
jjazzboss

Reputation: 1422

Here is the missing code:

  // To find the available Midi IN devices on your system, scan the available MidiDevices 
  // and test if (!(device instanceof Sequencer) && device.getMaxTransmitters() != 0)
  // ...
  inDevice.open();
 
 // tIn will transmit Midi IN data. Don't forget to close it when no longer used
  Transmitter tIn = inDevice.getTransmitter();
  
  // Connect it to our MidiMessage handler
  tIn.setReceiver(new MidiInMessageHandler());               

  // ...

  class MidiInMessageHandler implements Receiver
    {
        @Override
        public void send(MidiMessage message, long timeStamp)
        {
            if (message instanceof SysexMessage)
            {
                // Do something
            }
        }

        @Override
        public void close()
        {
            // Nothing
        }        
    }

If you need more example code check out my application JJazzLab-X on GitHub, especially JJazzMidiSystem.java and MidiUtilities.java in the Midi module.

Upvotes: 2

Related Questions