Java将midi消息发送到设备

时间:2018-05-18 12:07:22

标签: java midi

我有一个APC40 MkII连接到树莓派。在pi上,我有java运行。使用java.sound.midi包,我可以建立到APC的连接并接收其midi消息而没有问题。但经过大量研究后,我仍然不知道如何将midi消息发送给APC。

这是我到目前为止的代码:

package lightorgansandbox;

import javax.sound.midi.*;
import java.util.List;


public class MidiHandler {

public MidiHandler() {
    MidiDevice device;
    MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo();

    for (MidiDevice.Info info : infos) {

        System.out.println("Info: '" + info.toString() + "'");

        try {
            device = MidiSystem.getMidiDevice(info);

            List<Transmitter> transmitters = device.getTransmitters();

            for(int j = 0; j<transmitters.size();j++) {
                transmitters.get(j).setReceiver(new MidiInputReceiver(device.getDeviceInfo().toString()));
            }  

            Transmitter trans = device.getTransmitter();
            trans.setReceiver(new MidiInputReceiver(device.getDeviceInfo().toString()));

            device.open();

        }catch (MidiUnavailableException e) {}
    }
}

public class MidiInputReceiver implements Receiver {

    public String name;

    public MidiInputReceiver(String name) {
        this.name = name;
    }

    public void send(MidiMessage msg, long timeStamp) {

        if (msg instanceof ShortMessage) {
            ShortMessage shortMessage = (ShortMessage) msg;

            int channel = shortMessage.getChannel();
            int pitch = shortMessage.getData1();
            int vel = shortMessage.getData2();
            System.out.println("Channel: " + channel);
            System.out.println("Pitch: " + pitch);
            System.out.println("vel: " + vel);

        }

    }

    public void close() {}

}

}

这一切都按我想要的方式运作。但是在哪里可以将消息发送回设备?

1 个答案:

答案 0 :(得分:1)

只需将消息发送到设备的接收器即可。 来自documentation

  Receiver rcvr = MidiSystem.getReceiver();  /* or device.getReceiver() */

  ShortMessage myMsg = new ShortMessage();
  myMsg.setMessage(ShortMessage.NOTE_ON, 0, 60, 93);
  long timeStamp = -1;
  rcvr.send(myMsg, timeStamp);