I'm trying to get all MIDI devices in Java, which was harder than I thought...
I tried the foreach()
loop, but it won't work because I don't know what ArrayList
I am using this method on.
Here is my code:
package com.example.cmmp.midi;
import javax.sound.midi.*;
import javax.sound.midi.spi.MidiDeviceProvider;
import java.util.*;
@SuppressWarnings("unchecked")
public class MidiDeviceReceiver {
private static MidiSystem MidiDevice;
public static Sequencer getSequencer() throws MidiUnavailableException {
return MidiSystem.getSequencer ();
}
public static List<MidiDevice> getMidiDevices(){
javax.sound.midi.MidiDeviceReceiver midiDeviceReceiver = new javax.sound.midi.MidiDeviceReceiver () {
public MidiSystem MidiDevice;
public void send(MidiMessage message, long timeStamp) {
}
public void close() {
}
public MidiDevice getMidiDevice() {
MidiDeviceProvider midi = new MidiDeviceProvider () {
public MidiDevice.Info[] getDeviceInfo() {
return new MidiDevice.Info[0];
}
public MidiDevice getDevice(MidiDevice.Info info) {
try {
MidiDevice = (MidiSystem) MidiSystem.getMidiDevice ( info );
} catch (MidiUnavailableException e) {
e.printStackTrace ();
}
return (javax.sound.midi.MidiDevice) MidiDevice;
}
};
return (javax.sound.midi.MidiDevice) MidiDevice;
}
};
return (List<javax.sound.midi.MidiDevice>) MidiDevice;
}
}
Any help would be appreciated.
CodePudding user response:
You can enumerate all the MidiDevices like this:
package org.example2;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
public class App2 {
public static void main(String[] args) throws MidiUnavailableException {
MidiDevice.Info[] devices = MidiSystem.getMidiDeviceInfo();
for (MidiDevice.Info info : devices) {
try {
MidiDevice device = MidiSystem.getMidiDevice(info);
System.out.println(info.getDescription() " " device.toString());
} catch (MidiUnavailableException e) {
System.out.println("Device " info.getDescription() " is not available");
e.printStackTrace();
}
}
}
}
Of course this gives you a static list of the devices which were present when you called the function -- if someone plugs in/unplugs a device, then the list will be out of date.