Skip to content

Commit

Permalink
Add basic MIDI functionality
Browse files Browse the repository at this point in the history
Adds a MIDIDevice class that wraps a reciever device and a transmitter device, and adds MIDI functionality to the TestControlMIDI.
  • Loading branch information
CoffeeCoder1 committed Oct 10, 2024
1 parent 0edeb78 commit 53698a7
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,22 +1,39 @@
package io.github.roboblazers7617.buttonbox.controls;

import javax.sound.midi.ShortMessage;
import javax.sound.midi.InvalidMidiDataException;

import io.github.roboblazers7617.buttonbox.midi.MIDIDevice;

/**
* A test {@link io.github.roboblazers7617.buttonbox.Control} that reads the data published by a {@link io.github.roboblazers7617.buttonbox.controls.TestControl} and outputs it as MIDI messages.
*/
public class TestControlMIDI extends TestControl {
private final MIDIDevice midiDevice;

/**
* Creates a new TestControlMIDI.
*
* @param id
* The ID string for the TestControlMIDI to use.
* @param midiDevice
* The MIDI device to send messages to.
* @see io.github.roboblazers7617.buttonbox.Control
*/
public TestControlMIDI(String id) {
public TestControlMIDI(String id, MIDIDevice midiDevice) {
super(id);
this.midiDevice = midiDevice;
}

@Override
public void updateHardware() {
System.out.println(getValue());
try {
ShortMessage message = new ShortMessage();
message.setMessage(ShortMessage.CONTROL_CHANGE, 0, 0, (int) (getValue() % 127));
midiDevice.send(message);
} catch (InvalidMidiDataException ex) {
System.err.println("Invalid MIDI data!");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package io.github.roboblazers7617.buttonbox.midi;

import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Receiver;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.Transmitter;

public class MIDIDevice {
private final MidiDevice rxDevice;
private final MidiDevice txDevice;
private final Receiver receiver;
private final Transmitter transmitter;

/**
* Wrapper for {@link MidiDevice}
*
* @param rxDevice
* {@link MidiDevice} to use for receiving messages
* @param txDevice
* {@link MidiDevice} to use for transmitting messages
* @implNote
* Provided devices must already be opened.
*/
public MIDIDevice(MidiDevice rxDevice, MidiDevice txDevice) throws MidiUnavailableException {
this.rxDevice = rxDevice;
this.txDevice = txDevice;
this.receiver = rxDevice.getReceiver();
this.transmitter = txDevice.getTransmitter();
}

public void send(ShortMessage message) {
receiver.send(message, -1);
}
}

0 comments on commit 53698a7

Please sign in to comment.