Java Code Examples for javax.sound.midi.MidiDevice#open()

The following examples show how to use javax.sound.midi.MidiDevice#open() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: bug6186488.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    MidiDevice/*Synthesizer*/ synth = null;

    try {
        synth = MidiSystem.getSynthesizer();
        //synth = MidiSystem.getMidiDevice(infos[0]);

        System.out.println("Synthesizer: " + synth.getDeviceInfo());
        synth.open();
        MidiMessage msg = new GenericMidiMessage(0x90, 0x3C, 0x40);
        //ShortMessage msg = new ShortMessage();
        //msg.setMessage(0x90, 0x3C, 0x40);

        synth.getReceiver().send(msg, 0);
        Thread.sleep(2000);

    } catch (Exception ex) {
        ex.printStackTrace();
        throw ex;
    } finally {
        if (synth != null && synth.isOpen())
            synth.close();
    }
    System.out.print("Did you heard a note? (enter 'y' or 'n') ");
    int result = System.in.read();
    System.in.skip(1000);
    if (result == 'y' || result == 'Y')
    {
        System.out.println("Test passed sucessfully.");
    }
    else
    {
        System.out.println("Test FAILED.");
        throw new RuntimeException("Test failed.");
    }
}
 
Example 2
Source File: InstrumentTester.java    From jsyn with Apache License 2.0 6 votes vote down vote up
public int setupMidiKeyboard() throws MidiUnavailableException, IOException, InterruptedException {
    messageParser = new MyParser();

    int result = 2;
    MidiDevice keyboard = MidiDeviceTools.findKeyboard();
    Receiver receiver = new CustomReceiver();
    // Just use default synthesizer.
    if (keyboard != null) {
        // If you forget to open them you will hear no sound.
        keyboard.open();
        // Put the receiver in the transmitter.
        // This gives fairly low latency playing.
        keyboard.getTransmitter().setReceiver(receiver);
        System.out.println("Play MIDI keyboard: " + keyboard.getDeviceInfo().getDescription());
        result = 0;
    } else {
        System.out.println("Could not find a keyboard.");
    }
    return result;
}
 
Example 3
Source File: UseMidiKeyboard.java    From jsyn with Apache License 2.0 6 votes vote down vote up
public int test() throws MidiUnavailableException, IOException, InterruptedException {
    setupSynth();

    int result = 2;
    MidiDevice keyboard = MidiDeviceTools.findKeyboard();
    Receiver receiver = new CustomReceiver();
    // Just use default synthesizer.
    if (keyboard != null) {
        // If you forget to open them you will hear no sound.
        keyboard.open();
        // Put the receiver in the transmitter.
        // This gives fairly low latency playing.
        keyboard.getTransmitter().setReceiver(receiver);
        System.out.println("Play MIDI keyboard: " + keyboard.getDeviceInfo().getDescription());
        result = 0;
    } else {
        System.out.println("Could not find a keyboard.");
    }
    return result;
}
 
Example 4
Source File: TestMidiLoop.java    From jsyn with Apache License 2.0 6 votes vote down vote up
public int test() throws MidiUnavailableException, IOException, InterruptedException {

        int result = -1;
        MidiDevice keyboard = MidiDeviceTools.findKeyboard();
        Receiver receiver = new CustomReceiver();
        // Just use default synthesizer.
        if (keyboard != null) {
            // If you forget to open them you will hear no sound.
            keyboard.open();
            // Put the receiver in the transmitter.
            // This gives fairly low latency playing.
            keyboard.getTransmitter().setReceiver(receiver);
            System.out.println("Play MIDI keyboard: " + keyboard.getDeviceInfo().getDescription());
            result = 0;
            Thread.sleep(4000);
            System.out.println("Close the keyboard. It may not work after this according to the docs!");
            keyboard.close();
        } else {
            System.out.println("Could not find a keyboard.");
        }
        return result;
    }
 
Example 5
Source File: PassportMidiInterface.java    From jace with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void resume() {
    if (isRunning() && midiOut != null) {
        return;
    }
    try {
        MidiDevice selectedDevice = MidiSystem.getSynthesizer();
        MidiDevice.Info[] devices = MidiSystem.getMidiDeviceInfo();
        if (devices.length == 0) {
            System.out.println("No MIDI devices found");
        } else {
            for (MidiDevice.Info dev : devices) {
                if (MidiSystem.getMidiDevice(dev).getMaxReceivers() == 0) {
                    continue;
                }
                System.out.println("MIDI Device found: " + dev);
                if ((preferredMidiDevice.getValue() == null && dev.getName().contains("Java Sound") && dev instanceof Synthesizer) ||
                        preferredMidiDevice.getValue().equalsIgnoreCase(dev.getName())
                    ) {
                    selectedDevice = MidiSystem.getMidiDevice(dev);
                    break;
                }
            }
        }
        if (selectedDevice != null) {
            System.out.println("Selected MIDI device: " + selectedDevice.getDeviceInfo().getName());
            selectedDevice.open();
            midiOut = selectedDevice.getReceiver();
            super.resume();
        }
    } catch (MidiUnavailableException ex) {
        System.out.println("Could not open MIDI synthesizer");
        Logger.getLogger(PassportMidiInterface.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 6
Source File: InstrumentTester.java    From jsyn with Apache License 2.0 6 votes vote down vote up
public int setupMidiKeyboard() throws MidiUnavailableException, IOException, InterruptedException {
    messageParser = new MyParser();

    int result = 2;
    MidiDevice keyboard = MidiDeviceTools.findKeyboard();
    Receiver receiver = new CustomReceiver();
    // Just use default synthesizer.
    if (keyboard != null) {
        // If you forget to open them you will hear no sound.
        keyboard.open();
        // Put the receiver in the transmitter.
        // This gives fairly low latency playing.
        keyboard.getTransmitter().setReceiver(receiver);
        System.out.println("Play MIDI keyboard: " + keyboard.getDeviceInfo().getDescription());
        result = 0;
    } else {
        System.out.println("Could not find a keyboard.");
    }
    return result;
}
 
Example 7
Source File: UseMidiKeyboard.java    From jsyn with Apache License 2.0 6 votes vote down vote up
public int test() throws MidiUnavailableException, IOException, InterruptedException {
    setupSynth();

    int result = 2;
    MidiDevice keyboard = MidiDeviceTools.findKeyboard();
    Receiver receiver = new CustomReceiver();
    // Just use default synthesizer.
    if (keyboard != null) {
        // If you forget to open them you will hear no sound.
        keyboard.open();
        // Put the receiver in the transmitter.
        // This gives fairly low latency playing.
        keyboard.getTransmitter().setReceiver(receiver);
        System.out.println("Play MIDI keyboard: " + keyboard.getDeviceInfo().getDescription());
        result = 0;
    } else {
        System.out.println("Could not find a keyboard.");
    }
    return result;
}
 
Example 8
Source File: TestMidiLoop.java    From jsyn with Apache License 2.0 6 votes vote down vote up
public int test() throws MidiUnavailableException, IOException, InterruptedException {

        int result = -1;
        MidiDevice keyboard = MidiDeviceTools.findKeyboard();
        Receiver receiver = new CustomReceiver();
        // Just use default synthesizer.
        if (keyboard != null) {
            // If you forget to open them you will hear no sound.
            keyboard.open();
            // Put the receiver in the transmitter.
            // This gives fairly low latency playing.
            keyboard.getTransmitter().setReceiver(receiver);
            System.out.println("Play MIDI keyboard: " + keyboard.getDeviceInfo().getDescription());
            result = 0;
            Thread.sleep(4000);
            System.out.println("Close the keyboard. It may not work after this according to the docs!");
            keyboard.close();
        } else {
            System.out.println("Could not find a keyboard.");
        }
        return result;
    }
 
Example 9
Source File: MidiReciever.java    From Panako with GNU Affero General Public License v3.0 5 votes vote down vote up
public MidiReciever()
    {
        MidiDevice device;
        MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo();
        for (int i = 0; i < infos.length; i++) {
            try {
            device = MidiSystem.getMidiDevice(infos[i]);
            //does the device have any transmitters?
            //if it does, add it to the device list
            System.out.println(infos[i]);

            //get all transmitters
            List<Transmitter> transmitters = device.getTransmitters();
            //and for each transmitter

            for(int j = 0; j<transmitters.size();j++) {
                //create a new receiver
                transmitters.get(j).setReceiver(
                        //using my own MidiInputReceiver
                        new MidiInputReceiver(device.getDeviceInfo().toString())
                );
            }

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

            //open each device
            device.open();
            //if code gets this far without throwing an exception
            //print a success message
            System.out.println(device.getDeviceInfo()+" Was Opened");


        } catch (MidiUnavailableException e) {}
    }


}
 
Example 10
Source File: Reopen.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static boolean doTest(int numIterations, boolean input) throws Exception {
    MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo();
    MidiDevice outDevice = null;
    MidiDevice inDevice = null;
    for (int i = 0; i < infos.length; i++) {
        MidiDevice device = MidiSystem.getMidiDevice(infos[i]);
        if (! (device instanceof Sequencer) &&
            ! (device instanceof Synthesizer)) {
            if (device.getMaxReceivers() != 0) {
                outDevice = device;
            }
            if (device.getMaxTransmitters() != 0) {
                inDevice = device;
            }
        }
    }
    MidiDevice testDevice = null;
    if (input) {
        testDevice = inDevice;
    } else {
        testDevice = outDevice;
    }
    if (testDevice == null) {
        out("Cannot test: device not available.");
        return true;
    }
    out("Using Device: " + testDevice);

    for (int i = 0; i < numIterations; i++) {
        out("@@@ ITERATION: " + i);
        testDevice.open();
        // This sleep ensures that the thread of MidiInDevice is started.
        sleep(50);
        testDevice.close();
    }
    return true;
}
 
Example 11
Source File: MidiCommunication.java    From jmg with GNU General Public License v2.0 5 votes vote down vote up
private void setMidiInputSelection(int inputDeviceID, MidiDevice.Info[] info) {
    try {
        // inut setup
        MidiDevice inputPort = MidiSystem.getMidiDevice (info [inputDeviceID]);
        //System.out.println (inputPort);
        inputPort.open ();
        Transmitter t = inputPort.getTransmitter ();
        t.setReceiver(this);
    } catch (Exception e) {
        // Oops! Should never get here
        System.out.println ("Exception in PlumStone main ()");
        System.out.println (e);
        System.exit (0);
    }
}
 
Example 12
Source File: MidiCommunication.java    From jmg with GNU General Public License v2.0 5 votes vote down vote up
private void setMidiOutputSelection(int outputDeviceID, MidiDevice.Info[] info) {
    try {
        // output setup
        MidiDevice outputPort = MidiSystem.getMidiDevice(info [outputDeviceID]);
        outputPort.open();
        this.midiReceiver = outputPort.getReceiver();
        //System.out.println("setMR = " + midiReceiver);
    } catch (Exception e) {
        // Oops! Should never get here
        System.out.println ("Exception in PlumStone main ()");
        System.out.println (e);
        System.exit (0);
    }
}
 
Example 13
Source File: MidiHandler.java    From haxademic with MIT License 5 votes vote down vote up
protected void initDevices(){
	MidiDevice device;
	MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo();
	
	allTransmitters = new ArrayList<Transmitter>();
	
	for (int i = 0; i < infos.length; i++) {
		try {
			device = MidiSystem.getMidiDevice(infos[i]);
			// does the device have any transmitters?
			// if it does, add it to the device list
			System.out.println(infos[i]);
			    			
			//get all transmitters
			List<Transmitter> transmitters = device.getTransmitters();
			// and for each transmitter create a new receiver using our own MidiInputReceiver
			for(int j = 0; j < transmitters.size(); j++ ) {
				Receiver receiver = new MidiInputReceiver(device.getDeviceInfo().toString());
				transmitters.get(j).setReceiver(receiver);
			}
			
			// open each device
			device.open();
			
			// store transmitter for each device
			allTransmitters.add(device.getTransmitter());
			
			// if code gets this far without throwing an exception print a success message
			System.out.println(device.getDeviceInfo()+" was opened");

		} catch (MidiUnavailableException e) {}
	}
}
 
Example 14
Source File: MidiOutGetMicrosecondPositionBug.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private static void testDevice(MidiDevice device) throws Exception {
    boolean timestampsAvailable = false;
    boolean timestampPrecisionOk = false;
    try {
        // expected behaviour if not opened?
        device.open();
        /* First, we're testing if timestamps are provided at all.
           Returning -1 (unsupported), while allowed by the API
           specification, is not sufficient to pass this test. */
        long timestamp = device.getMicrosecondPosition();
        timestampsAvailable = (timestamp != -1);

        /* Then, we're testing the precision. Note that the system time
           is measured in milliseconds, while the device time is measured
           in microseconds. */

        long systemTime1 = System.currentTimeMillis();
        long deviceTime1 = device.getMicrosecondPosition();
        // rest for 5 seconds
        Thread.sleep(5000);
        long systemTime2 = System.currentTimeMillis();
        long deviceTime2 = device.getMicrosecondPosition();

        // now both period measurements are calculated in milliseconds.
        long systemDuration = systemTime2 - systemTime1;
        long deviceDuration = (deviceTime2 - deviceTime1) / 1000;
        long delta = Math.abs(systemDuration - deviceDuration);
        // a deviation of 0.5 seconds (= 500 ms) is allowed.
        timestampPrecisionOk = (delta <= 500);
    } catch (Throwable t) {
        System.out.println("  - Caught exception. Not failed.");
        System.out.println("  - " + t.toString());
        return;
    } finally {
        device.close();
    }
    if (! timestampsAvailable) {
        throw new Exception("timestamps are not supported");
    }
    if (! timestampPrecisionOk) {
        throw new Exception("device timer not precise enough");
    }
    successfulTests++;
}
 
Example 15
Source File: VolumeScalingReceiver.java    From mochadoom with GNU General Public License v3.0 4 votes vote down vote up
/** Guess how suitable a MidiDevice is for music output. */
private float score(MidiDevice.Info info) {
    String lcName = info.getName().toLowerCase(Locale.ENGLISH);
    float result = 0f;
    try {
        MidiDevice dev = MidiSystem.getMidiDevice(info);
        dev.open();
        try {
            if (dev instanceof Sequencer) {
                // The sequencer cannot be the same device as the synthesizer - that would create an infinite loop.
                return Float.NEGATIVE_INFINITY;
            } else if (lcName.contains("mapper")) {
                // "Midi Mapper" is ideal, because the user can select the default output device in the control panel
                result += 100;
            } else {
                if (dev instanceof Synthesizer) {
                    // A synthesizer is usually better than a sequencer or USB MIDI port
                    result += 50;
                    if (lcName.contains("java")) {
                        // "Java Sound Synthesizer" often has a low sample rate or no default soundbank;  Prefer another software synth
                        if (((Synthesizer) dev).getDefaultSoundbank() != null) {
                            result -= 10;
                        } else {
                            // Probably won't be audible
                            result -= 500;
                        }
                    }
                    if (lcName.contains("microsoft")) {
                        // "Microsoft GS Wavetable Synth" is notoriously unpopular, but sometimes it's the only one
                        // with a decent sample rate.
                        result -= 7;
                    }
                }
            }
            return result;
        } finally {
            dev.close();
        }
    } catch (MidiUnavailableException ex) {
        // Cannot use this one
        return Float.NEGATIVE_INFINITY;
    }
}