Java Code Examples for javax.sound.midi.MidiSystem#getSynthesizer()

The following examples show how to use javax.sound.midi.MidiSystem#getSynthesizer() . 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: MidiTest.java    From kyoko with MIT License 7 votes vote down vote up
public static void main(String... args) throws MidiUnavailableException, IOException, InvalidMidiDataException {
    var synth = MidiSystem.getSynthesizer();
    synth.loadAllInstruments(synth.getDefaultSoundbank());

    var sequencer = MidiSystem.getSequencer();
    var sequence = MidiSystem.getSequence(new File("test.mid"));

    // sequencer.getTransmitter().setReceiver(synth.getReceiver());
    sequencer.open();
    sequencer.setSequence(sequence);
    sequencer.setTempoFactor(1f);
    sequencer.addMetaEventListener(meta -> {
        if (meta.getType() == 47) { // track end
            sequencer.setTickPosition(0);
            sequencer.start();
        }
    });
    sequencer.start();
}
 
Example 2
Source File: ExtraCharInSoundbank.java    From openjdk-jdk9 with GNU General Public License v2.0 7 votes vote down vote up
public static void main(String[] args) throws Exception {
    // the internal synthesizer needs a soundcard to work properly
    if (!isSoundcardInstalled()) {
        return;
    }
    Synthesizer theSynth = MidiSystem.getSynthesizer();
    System.out.println("Got synth: "+theSynth);
    theSynth.open();
    try {
        Soundbank theSoundbank = theSynth.getDefaultSoundbank();
        System.out.println("Got soundbank: "+theSoundbank);
        theSynth.loadAllInstruments(theSoundbank);
        try {
                if (!checkInstrumentNames(theSynth)) {
                        throw new Exception("Test failed");
                }
        } finally {
                theSynth.unloadAllInstruments(theSoundbank);
        }
    } finally {
        theSynth.close();
    }
    System.out.println("Test passed.");
}
 
Example 3
Source File: Midi2WavRenderer.java    From computoser with GNU Affero General Public License v3.0 7 votes vote down vote up
public static AudioSynthesizer findAudioSynthesizer() throws MidiUnavailableException, IOException, InvalidMidiDataException {
    // First check if default synthesizer is AudioSynthesizer.
    Synthesizer synth = MidiSystem.getSynthesizer();
    if (synth instanceof AudioSynthesizer) {
        return (AudioSynthesizer) synth;
    }

    // If default synhtesizer is not AudioSynthesizer, check others.
    Info[] infos = MidiSystem.getMidiDeviceInfo();
    for (int i = 0; i < infos.length; i++) {
        MidiDevice dev = MidiSystem.getMidiDevice(infos[i]);
        if (dev instanceof AudioSynthesizer) {
            return (AudioSynthesizer) dev;
        }
    }

    // No AudioSynthesizer was found, return null.
    return null;
}
 
Example 4
Source File: Dialogs.java    From Pixelitor with GNU General Public License v3.0 7 votes vote down vote up
public static void playWarningSound() {
    try {
        int maxVolume = 90;
        int sound = 65;
        Synthesizer synthesizer = MidiSystem.getSynthesizer();
        synthesizer.open();
        MidiChannel channel = synthesizer.getChannels()[9];  // drums channel.
        for (int i = 0; i < 10; i++) {
            Thread.sleep(100);
            channel.noteOn(sound + i, maxVolume);
            Thread.sleep(100);
            channel.noteOff(sound + i);
        }
    } catch (MidiUnavailableException | InterruptedException e1) {
        e1.printStackTrace();
    }
}
 
Example 5
Source File: MidiSynth.java    From jmg with GNU General Public License v2.0 7 votes vote down vote up
private boolean initSynthesizer() {
    if (null == m_synth) {
        try {
            if (MidiSystem.getSequencer() == null) {
                System.err.println("MidiSystem Sequencer Unavailable");
                return false;
            }

            m_synth = MidiSystem.getSynthesizer();
            m_synth.open();
            m_sequencer = MidiSystem.getSequencer();
            //m_sequencer.open();
        }
        catch (MidiUnavailableException e) {
            System.err.println("Midi System Unavailable:" + e);
            return false;
        }
    }
    return true;
}
 
Example 6
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 7
Source File: MidiApp.java    From FXTutorials with MIT License 6 votes vote down vote up
private void loadChannel() {
    try {
        Synthesizer synth = MidiSystem.getSynthesizer();
        synth.open();
        synth.loadInstrument(synth.getDefaultSoundbank().getInstruments()[5]);

        channel = synth.getChannels()[0];

    } catch (MidiUnavailableException e) {
        System.out.println("Cannot get synth");
        e.printStackTrace();
    }
}
 
Example 8
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 9
Source File: DefaultDevices.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static boolean testDevice(MidiDevice device, Class type,
        String providerClassName, String instanceName,
        boolean expectedResult) {
    boolean allOk = true;

    try {
        String propertyName = type.getName();
        String propertyValue = (providerClassName != null) ? providerClassName: "" ;
        propertyValue += "#" + instanceName;
        out("property: " + propertyName + "="+ propertyValue);
        System.setProperty(propertyName, propertyValue);
        Object reference = null;
        Object result = null;
        if (type == SEQUENCER_CLASS) {
            reference = device;
            result = MidiSystem.getSequencer();
        } else if (type == SYNTHESIZER_CLASS) {
            reference = device;
            result = MidiSystem.getSynthesizer();
        } else if (type == RECEIVER_CLASS) {
            reference = device.getReceiver();
            result = MidiSystem.getReceiver();
        } else if (type == TRANSMITTER_CLASS) {
            reference = device.getTransmitter();
            result = MidiSystem.getTransmitter();
        }
        out("result: " + result);
        boolean rightDevice = (reference.getClass() == result.getClass());
        if (rightDevice != expectedResult) {
            out("\nERROR: type " + type + " failed:"
                    + " class should" + (expectedResult ? "" : " NOT") + " be '"
                    + reference.getClass()
                    + "' but is '" + result.getClass() + "'!\n");
            allOk = false;
        }
        if (expectedResult
                && reference instanceof MidiDevice
                && result instanceof MidiDevice) {
            MidiDevice referenceDevice = (MidiDevice)reference;
            MidiDevice resultDevice = (MidiDevice)result;
            if (!referenceDevice.getDeviceInfo().getName().equals(
                                resultDevice.getDeviceInfo().getName())) {
                out("\nERROR: type " + type + " failed: name should be '"
                        + referenceDevice.getDeviceInfo().getName()
                        + "' but is '"
                        + resultDevice.getDeviceInfo().getName() + "'!\n");
                allOk = false;
            }
        }
        if (result instanceof Receiver) {
            ((Receiver)result).close();
        } else if (result instanceof Transmitter) {
            ((Transmitter)result).close();
        } else if (result instanceof Synthesizer) {
            ((Synthesizer)result).close();
        } else if (result instanceof Sequencer) {
            ((Sequencer)result).close();
        }
    } catch (Exception e) {
        out("Exception thrown; Test NOT failed.");
        e.printStackTrace(System.out);
        out("");
    }
    return allOk;
}
 
Example 10
Source File: bug4685396.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static boolean test(
        boolean reloadInstr,    // reload all instruments?
        boolean unloadFrom,     // unload "from" instrument?
        boolean unloadTo        // unload "to" instrument?
        ) throws MidiUnavailableException {
    log("Starting test: reloadInstr=" + reloadInstr
            + ", unloadFrom=" + unloadFrom
            + ", unloadTo=" + unloadTo
            + "");

    log("  creating synthesizer...");
    synth = MidiSystem.getSynthesizer();
    log("  opening synthesizer...");
    synth.open();

    Soundbank sbank = synth.getDefaultSoundbank();
    if (sbank == null)
        throw new RuntimeException("ERROR: Could not get default soundbank");

    if (reloadInstr) {
        synth.unloadAllInstruments(sbank);
        synth.loadAllInstruments(sbank);
    }

    Instrument[] instrs = synth.getLoadedInstruments();

    log("  " + instrs.length + " instruments loaded.");

    if (instrs.length < 2)
        throw new RuntimeException("ERROR: need at least 2 loaded instruments");

    Instrument from = instrs[0];
    Instrument to = instrs[instrs.length - 1];

    if (unloadFrom)
        synth.unloadInstrument(from);
    if (unloadTo)
        synth.unloadInstrument(to);

    log("  from instrument (" + (unloadFrom ? "UNLOADED" : "LOADED")
                            + "): " + from.toString());
    log("  to instrument (" + (unloadTo ? "UNLOADED" : "LOADED")
                            + "): " + to.toString());

    boolean result = false;
    boolean excepted = false;
    try {
        result = synth.remapInstrument(from, to);
        log("  remapInstrument(from, to) returns " + result);
    } catch (IllegalArgumentException ex) {
        excepted = true;
        log("  EXCEPTION:");
        ex.printStackTrace(System.out);
    }

    instrs = synth.getLoadedInstruments();
    log("  " + instrs.length + " instruments remains loaded.");

    boolean toUnloaded = !isInstrumentExist(to, instrs);
    boolean fromUnloaded = !isInstrumentExist(from, instrs);

    log("  from instrument is " + (fromUnloaded ? "UNLOADED" : "LOADED"));
    log("  to instrument is " + (toUnloaded ? "UNLOADED" : "LOADED"));

    boolean bOK = true;
    if (result) {
        if (unloadTo) {
            bOK = false;
            log("ERROR: unloaded to, but sucessfull remap");
        }
        if (!fromUnloaded) {
            bOK = false;
            log("ERROR: sucessfull remap, but from hasn't been unloaded");
        }
        if (toUnloaded) {
            bOK = false;
            log("ERROR: to has been unloaded!");
        }
    } else {
        if (!excepted) {
            bOK = false;
            log("ERROR: remap returns false, exception hasn't been thrown");
        }
        if (!unloadTo) {
            bOK = false;
            log("ERROR: to is loaded, but remap returns false");
        }
        if (unloadFrom != fromUnloaded) {
            bOK = false;
            log("ERROR: remap returns false, but status of from has been changed");
        }
    }

    if (bOK) {
        log("Test result: OK\n");
    } else {
        log("Test result: FAIL\n");
    }

    return bOK;
}
 
Example 11
Source File: AsynchronousMidiChannel.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void doIt(String args[]) {
    Synthesizer synth = null;
    MidiChannel mChanArr[];
    MidiChannel chan = null;
    boolean failed = false;
    int i = 0;
    int chanNum = 0;

    int val = 1;
    int contr = 0;
    Soundbank sBank;
    Instrument[] insArr;
    Instrument instr = null;
    Object ev = new Object();

    try {
        synth = MidiSystem.getSynthesizer();
        System.out.println("Got synth: "+synth);
        synth.open();

        int latency = (int) synth.getLatency();
        System.out.println("  -> latency: "
                           +latency
                           +" microseconds");

        mChanArr = synth.getChannels();
        while ((i < mChanArr.length) && (chan == null)) {
            chanNum = i;
            chan = mChanArr[i++];
        }
        if (chan == null) {
            System.out.println("No channels in "
                               +"this synthesizer!");
            return;
        }
        System.out.println("Got MidiChannel: "+chan);


        sBank = synth.getDefaultSoundbank();
        if (sBank == null) {
            System.out.println("No default sound bank!");
            return;
        }


        insArr = sBank.getInstruments();
        for (int j = 0; j < insArr.length; j++) {
            if (insArr[j].getPatch().getBank() == val) {
                instr = insArr[j];
                synth.loadInstrument(instr);
            }
        }
        if (instr == null) {
            System.out.println("No instr. with this bank!");
            return;
        }

        chan.controlChange(contr, val);

        // need to respect the synthesizer's latency
        if (latency > 0) {
            try {
                Thread.sleep(latency/1000);
            } catch (InterruptedException inEx) {
            }
        }

        if (chan.getController(contr) != val) {
            failed = true;
            System.err.println("getController() does not "
                               +"return proper value: "
            + chan.getController(contr));
        }  else {
            System.out.println("getController("
            + contr + ") returns proper value: "
            + chan.getController(contr));
        }

    } catch (MidiUnavailableException mue) {
        System.err.println("MidiUnavailableException was "
                           +"thrown: " + mue);
        System.out.println("could not test.");
        return;
    } catch(SecurityException se) {
        se.printStackTrace();
        System.err.println("Sound access is not denied but "
        + "SecurityException was thrown!");
        return;

    } finally {
        if (synth != null) synth.close();
    }


    if (failed == true) {
        System.out.println("test failed");
    } else {
        System.out.println("OKAY");
    }
    return;
}
 
Example 12
Source File: SynthesizerGetLatency.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    Synthesizer synth = null;
    boolean failed = false;
    boolean notexec = false;
    try {
        synth = MidiSystem.getSynthesizer();
        System.out.println("Got synth: "+synth);
        synth.open();

        int latency = (int) synth.getLatency();
        System.out.println("  -> latency: "
                           +latency
                           +" microseconds");
        if (latency < 5000 && latency > 0) {
            System.out.println("## This latency is VERY small, probably due to this bug.");
            System.out.println("## This causes failure of this test.");
            failed = true;
        }
    } catch (MidiUnavailableException mue) {
        System.err.println("MidiUnavailableException was "
                           +"thrown: " + mue);
        System.out.println("could not test.");
        notexec = true;
    } catch(SecurityException se) {
        se.printStackTrace();
        System.err.println("Sound access is not denied but "
        + "SecurityException was thrown!");
        notexec = true;
    } finally {
        if (synth != null) synth.close();
    }


    if (failed) {
        throw new Exception("Test FAILED!");
    }
    if (notexec) {
        System.out.println("Test not failed.");
    } else {
        System.out.println("Test Passed.");
    }
}
 
Example 13
Source File: PlayMusicSkill.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public PlayMusicSkill() {

		try {
			// On récupère le synthétiseur, on l'ouvre et on obtient un canal
			synthetiseur = MidiSystem.getSynthesizer();
			synthetiseur.open();
		} catch (final MidiUnavailableException ex) {
			Logger.getLogger(PlayMusicSkill.class.getName()).log(Level.SEVERE, null, ex);
		}
		canal = synthetiseur.getChannels()[0];

		// On initialise l'instrument 0 (le piano) pour le canal
		canal.programChange(0);
	}