Java 类javax.sound.midi.MidiSystem 实例源码

项目:Gervill4Beads    文件:CaptureMidiMessages.java   
/**
 * Capture midi input events, dispatching them to given Receiver.
 * The MidiDevice returned is the device providing the input, and
 * should be closed when input events are no longer needed.
 * Note that this method returns the first MidiDevice which
 * has at least one transmitter.
 * 
 * @param receiver the Receiver to which midi input events should be dispatched
 * @return the MidiDevice providing the input events
 * @throws MidiUnavailableException if midi input can't be found
 */
public static MidiDevice getMidiInput(Receiver receiver) throws MidiUnavailableException {
    MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo();
    for (MidiDevice.Info info : infos) {
        MidiDevice device;
        device = MidiSystem.getMidiDevice(info);
        if (DEBUG) {
            System.out.println("Found: " + device);
        }

        int maxTransmitters = device.getMaxTransmitters();
        if (DEBUG) {
            System.out.println("  Max transmitters: " + maxTransmitters);
        }

        if (maxTransmitters == -1 || maxTransmitters > 0) {
            Transmitter transmitter = device.getTransmitter();
            transmitter.setReceiver(receiver);
            device.open();
            return device;
        }
    }

    throw new MidiUnavailableException("Could not find any midi input sources");
}
项目:LinkGame    文件:BackMusic.java   
public void play() {
    if (isPlaying) { // 如果已经在播放,返回
        return;
    }

    try {
        sequencer = MidiSystem.getSequencer();
        sequencer.open();
        sequencer.setSequence(sequence);
        sequencer.setLoopCount(Sequencer.LOOP_CONTINUOUSLY );
        sequencer.addMetaEventListener(this);
    } catch (InvalidMidiDataException ex) {
    } catch (MidiUnavailableException e) {
    }

    thread = new Thread(this);
    thread.start();
}
项目:jaer    文件:DrumSound.java   
private void open () throws MidiUnavailableException{
        synth = MidiSystem.getSynthesizer();
        MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo();
        MidiDevice.Info msInfo = null;
        StringBuilder sb = new StringBuilder();
        sb.append("Available MidiDevice are\n");
        for ( MidiDevice.Info i:infos ){
            if ( i.toString().contains("Microsoft GS Wavetable Synth") ){
                msInfo = i;
                sb.append(" *****");
            }
            sb.append("\t" + i.toString() + ": " + i.getDescription() + '\n');
        }
//        MidiDevice msDevice = MidiSystem.getMidiDevice(msInfo);
        synth.open();

        sb.append("synth=" + synth.getDeviceInfo().toString() + " with default soundbank " + synth.getDefaultSoundbank().getDescription() + '\n');
        sb.append("max synthesizer latency =" + synth.getLatency() + " us\n");
        log.info(sb.toString());
        channels = synth.getChannels();
        channel = channels[PERCUSSION_CHANNEL];
    }
项目:openjdk-jdk10    文件:DefaultDevices.java   
public static void main(String[] args) throws Exception {
    boolean allOk = true;
    MidiDevice.Info[] infos;

    out("\nTesting MidiDevices retrieved via MidiSystem");
    infos = MidiSystem.getMidiDeviceInfo();
    allOk &= testDevices(infos, null);

    out("\nTesting MidiDevices retrieved from MidiDeviceProviders");
    List providers = JDK13Services.getProviders(MidiDeviceProvider.class);
    for (int i = 0; i < providers.size(); i++) {
        MidiDeviceProvider provider = (MidiDeviceProvider)providers.get(i);
        infos = provider.getDeviceInfo();
        allOk &= testDevices(infos, provider.getClass().getName());
    }

    if (!allOk) {
        throw new Exception("Test failed");
    } else {
        out("Test passed");
    }
}
项目:openjdk-jdk10    文件:MidiFileTypeUniqueness.java   
public static void main(String[] args) throws Exception {
    boolean foundDuplicates = false;
    int[]   aTypes = MidiSystem.getMidiFileTypes();
    for (int i = 0; i < aTypes.length; i++)
    {
        for (int j = 0; j < aTypes.length; j++)
        {
            if (aTypes[i] == aTypes[j] && i != j) {
                foundDuplicates = true;
            }
        }
    }
    if (foundDuplicates) {
        throw new Exception("Test failed");
    } else {
        System.out.println("Test passed");
    }
}
项目:openjdk-jdk10    文件:UnsupportedInfo.java   
public static void main(final String[] args) {
    final MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo();
    for (final MidiDeviceProvider mdp : load(MidiDeviceProvider.class)) {
        for (final MidiDevice.Info info : infos) {
            if (mdp.isDeviceSupported(info)) {
                if (mdp.getDevice(info) == null) {
                    throw new RuntimeException("MidiDevice is null");
                }
            } else {
                try {
                    mdp.getDevice(info);
                    throw new RuntimeException(
                            "IllegalArgumentException expected");
                } catch (final IllegalArgumentException ignored) {
                    // expected
                }
            }
        }
    }
}
项目:openjdk-jdk10    文件:SeqStartRecording.java   
public static void main(String argv[]) {
    Sequencer seq = null;
    try {
        seq = MidiSystem.getSequencer();
        seq.open();
    } catch (final MidiUnavailableException ignored) {
        // the test is not applicable
        return;
    }
    try {
        seq.startRecording();
        System.out.println("Test passed.");
    } catch (NullPointerException npe) {
        System.out.println("Caught NPE: "+npe);
        npe.printStackTrace();
        throw new RuntimeException("Test FAILED!");
    } catch (Exception e) {
        System.out.println("Unexpected Exception: "+e);
        e.printStackTrace();
        System.out.println("Test NOT failed.");
    } finally {
        seq.close();
    }
}
项目:openjdk-jdk10    文件:OpenClose.java   
/**
 * Returns true if at least one MIDI (port) device is correctly installed on
 * the system.
 */
public static boolean isMidiInstalled() {
    boolean result = false;
    MidiDevice.Info[] devices = MidiSystem.getMidiDeviceInfo();
    for (int i = 0; i < devices.length; i++) {
        try {
            MidiDevice device = MidiSystem.getMidiDevice(devices[i]);
            result = ! (device instanceof Sequencer) && ! (device instanceof Synthesizer);
        } catch (Exception e1) {
            System.err.println(e1);
        }
        if (result)
            break;
    }
    return result;
}
项目:openjdk-jdk10    文件:ClosedReceiver.java   
/**
 * Execute Receiver.send() and expect that there is no exception.
 */
private static boolean testReceiverSend() {
    boolean result = true;

    Receiver receiver;
    ShortMessage shMsg = new ShortMessage();

    try {
        receiver = MidiSystem.getReceiver();
        shMsg.setMessage(ShortMessage.NOTE_ON, 0,60, 93);
        try {
            receiver.send( shMsg, -1 );
        } catch(IllegalStateException ilEx) {
            ilEx.printStackTrace(System.out);
            out("IllegalStateException was thrown incorrectly!");
            result = false;
        }
        receiver.close();
    } catch(MidiUnavailableException e) {
        out("Midi unavailable, cannot test.");
    } catch(InvalidMidiDataException ine) {
        out("InvalidMidiDataException, cannot test.");
    }
    return result;
}
项目:openjdk-jdk10    文件:ClosedReceiver.java   
/**
 * Returns true if at least one MIDI (port) device is correctly installed on
 * the system.
 */
private static boolean isMidiInstalled() {
    boolean result = false;
    MidiDevice.Info[] devices = MidiSystem.getMidiDeviceInfo();
    for (int i = 0; i < devices.length; i++) {
        try {
            MidiDevice device = MidiSystem.getMidiDevice(devices[i]);
            result = !(device instanceof Sequencer)
                    && !(device instanceof Synthesizer);
        } catch (Exception e1) {
            System.err.println(e1);
        }
        if (result)
            break;
    }
    return result;
}
项目:openjdk-jdk10    文件:ReceiverTransmitterAvailable.java   
private static void doAllTests() {
    boolean problemOccured = false;
    boolean succeeded = true;
    MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo();
    for (int i = 0; i < infos.length; i++) {
        MidiDevice device = null;
        try {
            device = MidiSystem.getMidiDevice(infos[i]);
            succeeded &= doTest(device);
        } catch (MidiUnavailableException e) {
            out("exception occured; cannot test");
            problemOccured = true;
        }
    }
    if (infos.length == 0) {
        out("Soundcard does not exist or sound drivers not installed!");
        out("This test requires sound drivers for execution.");
    }
    isTestExecuted = !problemOccured;
    isTestPassed = succeeded;
}
项目:openjdk-jdk10    文件:MidiOutGetMicrosecondPositionBug.java   
private static void doAll() throws Exception {
    MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo();
    for (int i=0; i < infos.length; i++) {
        MidiDevice device = MidiSystem.getMidiDevice(infos[i]);
        if ((! (device instanceof Sequencer)) &&
            (! (device instanceof Synthesizer)) &&
            (device.getMaxReceivers() > 0 || device.getMaxReceivers() == -1)) {

            System.out.println("--------------");
            System.out.println("Testing MIDI device: " + infos[i]);
            testDevice(device);
        }
        if (infos.length==0) {
            System.out.println("No MIDI devices available!");
        }
    }
}
项目:openjdk-jdk10    文件:MidiOutGetMicrosecondPositionBug.java   
/**
 * Returns true if at least one MIDI (port) device is correctly installed on
 * the system.
 */
public static boolean isMidiInstalled() {
    boolean result = false;
    MidiDevice.Info[] devices = MidiSystem.getMidiDeviceInfo();
    for (int i = 0; i < devices.length; i++) {
        try {
            MidiDevice device = MidiSystem.getMidiDevice(devices[i]);
            result = ! (device instanceof Sequencer) && ! (device instanceof Synthesizer);
        } catch (Exception e1) {
            System.err.println(e1);
        }
        if (result)
            break;
    }
    if (!result) {
        System.err.println("Soundcard does not exist or sound drivers not installed!");
        System.err.println("This test requires sound drivers for execution.");
    }
    return result;
}
项目:openjdk-jdk10    文件:GetSoundBankIOException.java   
public static void main(String args[]) throws Exception {
    boolean failed = false;
    try {
        String filename = "GetSoundBankIOException.java";
        System.out.println("Opening "+filename+" as soundbank...");
        File midiFile = new File(System.getProperty("test.src", "."), filename);
        MidiSystem.getSoundbank(midiFile);
        //Soundbank sBank = MidiSystem.getSoundbank(new NonMarkableIS());
        System.err.println("InvalidMidiDataException was not thrown!");
        failed = true;
    } catch (InvalidMidiDataException invMidiEx) {
        System.err.println("InvalidMidiDataException was thrown. OK.");
    } catch (IOException ioEx) {
        System.err.println("Unexpected IOException was caught!");
        System.err.println(ioEx.getMessage());
        ioEx.printStackTrace();
        failed = true;
    }

    if (failed) throw new Exception("Test FAILED!");
    System.out.println("Test passed.");
}
项目:openjdk-jdk10    文件:ExtraCharInSoundbank.java   
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.");
}
项目:openjdk9    文件:UnsupportedInfo.java   
public static void main(final String[] args) {
    final MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo();
    for (final MidiDeviceProvider mdp : load(MidiDeviceProvider.class)) {
        for (final MidiDevice.Info info : infos) {
            if (mdp.isDeviceSupported(info)) {
                if (mdp.getDevice(info) == null) {
                    throw new RuntimeException("MidiDevice is null");
                }
            } else {
                try {
                    mdp.getDevice(info);
                    throw new RuntimeException(
                            "IllegalArgumentException expected");
                } catch (final IllegalArgumentException ignored) {
                    // expected
                }
            }
        }
    }
}
项目:launchpad_s_plus    文件:MidiInDump.java   
public static void openInput() throws Exception {
    setup();

    if (bUseDefaultSynthesizer) {
        Synthesizer synth = MidiSystem.getSynthesizer();
        synth.open();
        r = synth.getReceiver();
        try {
            Transmitter t = launchpad_s_plus.Launchpad.getInputDevice()
                    .getTransmitter();
            t.setReceiver(r);
        } catch (MidiUnavailableException e) {
            out("wasn't able to connect the device's Transmitter to the default Synthesizer:");
            out(e);
            launchpad_s_plus.Launchpad.getInputDevice().close();
            System.exit(1);
        }
    }

    out("\nNow taking input.");

}
项目:launchpad_s_plus    文件:MidiCommon.java   
/**
 * Retrieve a MidiDevice.Info for a given name.
 * 
 * This method tries to return a MidiDevice.Info whose name matches the
 * passed name. If no matching MidiDevice.Info is found, null is returned.
 * If bForOutput is true, then only output devices are searched, otherwise
 * only input devices.
 * 
 * @param strDeviceName
 *            the name of the device for which an info object should be
 *            retrieved.
 * @param bForOutput
 *            If true, only output devices are considered. If false, only
 *            input devices are considered.
 * 
 * @return A MidiDevice.Info object matching the passed device name or null
 *         if none could be found.
 */
public static MidiDevice.Info getMidiDeviceInfo(String strDeviceName,
        boolean bForOutput) {
    MidiDevice.Info[] aInfos = MidiSystem.getMidiDeviceInfo();
    for (int i = 0; i < aInfos.length; i++) {
        if (aInfos[i].getName().contains(strDeviceName)) {
            try {
                MidiDevice device = MidiSystem.getMidiDevice(aInfos[i]);
                boolean bAllowsInput = (device.getMaxTransmitters() != 0);
                boolean bAllowsOutput = (device.getMaxReceivers() != 0);
                if ((bAllowsOutput && bForOutput)
                        || (bAllowsInput && !bForOutput)) {
                    return aInfos[i];
                }
            } catch (MidiUnavailableException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}
项目:LaunchPad-MC    文件:LaunchPad.java   
private void init() throws MidiUnavailableException {
    devIn = MidiSystem.getMidiDevice(inInfo); devIn.open();
    devOut = MidiSystem.getMidiDevice(outInfo); devOut.open();
    midiIn = new MidiInput(); devIn.getTransmitter().setReceiver(midiIn);
    midiOut = (MidiDeviceReceiver)devOut.getReceiver();

    //MIDI Message Sender Thread:
    midiTx = new Thread(() -> { while(true) {
        int size; while((size=cue.size()) > 0) {
            MidiMessage msg; synchronized(this) { msg = cue.get(0); cue.remove(0); } midiOut.send(msg, -1);
            if(size > 10000) { //Keep array under 10,000...
                synchronized(this) { size=cue.size(); while(size > 50) { cue.remove(size-1); size--; }}
                debug("Buffer had to be force-cleared!");
            } if(Thread.interrupted()) return;
        } if(Thread.interrupted()) return;
    }}); midiTx.setPriority(1); midiTx.start();

    programMode(); setAll(-1); //Reset LaunchPad Lights.
}
项目:iSeleda    文件:Dialogs.java   
private static void playWarningSound() {
//        if (2 > 1) {
//            return;
//        }

        try {
//            int velocity = 127;    // max volume
            int velocity = 90;    // max volume
            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, velocity);
                Thread.sleep(100);
                channel.noteOff(sound + i);
            }
        } catch (MidiUnavailableException | InterruptedException e1) {
            e1.printStackTrace();
        }
    }
项目:TuxGuitar-1.3.1-fork    文件:MidiToAudioSynth.java   
public void loadSoundbank(List<Patch> patchList, String soundbankPath) throws Throwable {
    Soundbank soundbank = null;
    if( soundbankPath == null || soundbankPath.length() == 0 ){
        soundbank = this.synthesizer.getDefaultSoundbank();
    } else{
        soundbank = MidiSystem.getSoundbank(new File(soundbankPath));
    }

    Iterator<Patch> it = patchList.iterator();
    while( it.hasNext() ){
        Patch patch = (Patch)it.next();

        boolean percussion = (patch.getBank() == 128);
        int bank = (percussion ? 0 : patch.getBank());
        int program = patch.getProgram();

        Instrument instrument = soundbank.getInstrument(createModelPatch(bank, program, percussion));
        if( instrument != null ){
            this.synthesizer.loadInstrument(instrument);
        }
    }
}
项目:TuxGuitar-1.3.1-fork    文件:MiPortProvider.java   
public static MidiDevice getDevice(String inDeviceName) throws MiException
{
MidiDevice.Info[]   infos = MidiSystem.getMidiDeviceInfo();

for(int i = 0; i < infos.length; i++)
    {
    if(infos[i].getName().equals(inDeviceName))
        {
        try {
            MidiDevice device = MidiSystem.getMidiDevice(infos[i]);

            if( device.getMaxTransmitters() == 0 ||
                device instanceof Sequencer)
                continue;

            return(device);
            }
        catch(MidiUnavailableException mue)
            {
            throw new MiException(TuxGuitar.getProperty("midiinput.error.midi.unavailable"), mue);
            }
        }
    }

return(null);
}
项目:TuxGuitar-1.3.1-fork    文件:MidiSynthesizerManager.java   
public Instrument findInstrument(Patch patch) {
    Instrument instrument = null;
    try {
        Patch resourcePatch = patch;
        InputStream inputStream = this.findResource(resourcePatch);
        if( inputStream == null ) {
            resourcePatch = this.toDefaultPatch(patch);
            if( resourcePatch.getBank() != patch.getBank() || resourcePatch.getProgram() != patch.getProgram() ) {
                inputStream = this.findResource(resourcePatch);
            }
        }
        if( inputStream != null ) {
            Soundbank soundbank = MidiSystem.getSoundbank(inputStream);
            if( soundbank != null ) {
                instrument = soundbank.getInstrument(this.toModelPatch(resourcePatch));
            }
        }
        if( instrument != null ) {
            this.setInstrumentPatch(instrument, patch);
        }
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }
    return instrument;
}
项目:ClearComposer    文件:MusicPlayer.java   
/**
 * This method initializes the MusicPlayer
 */
public static boolean init()
{
    try
    {
        if (synth == null)
            synth = MidiSystem.getSynthesizer();
        if (!synth.isOpen())
            synth.open();
        return true;
    } catch (MidiUnavailableException e)
    {
        e.printStackTrace();
        return false;
    }
}
项目:ether    文件:URLAudioSource.java   
private Synthesizer findAudioSynthesizer() throws MidiUnavailableException, ClassNotFoundException {
    Class<?> audioSynth = Class.forName("com.sun.media.sound.AudioSynthesizer");

    // First check if default synthesizer is AudioSynthesizer.
    Synthesizer synth = MidiSystem.getSynthesizer();
    if (audioSynth.isAssignableFrom(synth.getClass())) {
        return synth;
    }

    // If default synthesizer is not AudioSynthesizer, check others.
    MidiDevice.Info[] midiDeviceInfo = MidiSystem.getMidiDeviceInfo();
    for (int i = 0; i < midiDeviceInfo.length; i++) {
        MidiDevice dev = MidiSystem.getMidiDevice(midiDeviceInfo[i]);
        if (audioSynth.isAssignableFrom(dev.getClass())) {
            return (Synthesizer)dev;
        }
    }
    return null;
}
项目:Gervill4Beads    文件:CaptureMidiMessages.java   
/**
 * Get a list of MidiDevices which are advertised as having
 * at least one Transmitter.
 * 
 * @return list of MidiDevices
 * @throws MidiUnavailableException
 */
public static List<MidiDevice> getAvailableTransmitters() throws MidiUnavailableException {
    ArrayList<MidiDevice> result = new ArrayList<MidiDevice>();

    MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo();
    for (MidiDevice.Info info : infos) {
        MidiDevice device = MidiSystem.getMidiDevice(info);

        int maxTransmitters = device.getMaxTransmitters();

        if (maxTransmitters == -1 || maxTransmitters > 0) {
            result.add(device);
        }
    }

    return result;
}
项目:liquinth    文件:SynthesizerFrame.java   
public void actionPerformed( ActionEvent actionEvent ) {
    if( midiDevice != null ) {
        midiDevice.close();
        midiDevice = null;
    }
    if( midiInfo != null ) {
        try {
            midiDevice = MidiSystem.getMidiDevice( midiInfo );
            midiDevice.open();
            midiDevice.getTransmitter().setReceiver( midiReceiver );
        } catch( MidiUnavailableException exception ) {
            JOptionPane.showMessageDialog( SynthesizerFrame.this, exception.getMessage(),
                "Unable to open MIDI device", JOptionPane.ERROR_MESSAGE );
            if( midiDevice != null ) {
                midiDevice.close();
                midiDevice = null;
            }
        }
    }
}
项目:launchpad_s_plus    文件:MidiInDump.java   
public static void openInput() throws Exception {
    setup();

    if (bUseDefaultSynthesizer) {
        Synthesizer synth = MidiSystem.getSynthesizer();
        synth.open();
        r = synth.getReceiver();
        try {
            Transmitter t = launchpad_s_plus.Launchpad.getInputDevice()
                    .getTransmitter();
            t.setReceiver(r);
        } catch (MidiUnavailableException e) {
            out("wasn't able to connect the device's Transmitter to the default Synthesizer:");
            out(e);
            launchpad_s_plus.Launchpad.getInputDevice().close();
            System.exit(1);
        }
    }

    out("\nNow taking input.");

}
项目:launchpad_s_plus    文件:MidiCommon.java   
/**
 * Retrieve a MidiDevice.Info for a given name.
 * 
 * This method tries to return a MidiDevice.Info whose name matches the
 * passed name. If no matching MidiDevice.Info is found, null is returned.
 * If bForOutput is true, then only output devices are searched, otherwise
 * only input devices.
 * 
 * @param strDeviceName
 *            the name of the device for which an info object should be
 *            retrieved.
 * @param bForOutput
 *            If true, only output devices are considered. If false, only
 *            input devices are considered.
 * 
 * @return A MidiDevice.Info object matching the passed device name or null
 *         if none could be found.
 */
public static MidiDevice.Info getMidiDeviceInfo(String strDeviceName,
        boolean bForOutput) {
    MidiDevice.Info[] aInfos = MidiSystem.getMidiDeviceInfo();
    for (int i = 0; i < aInfos.length; i++) {
        if (aInfos[i].getName().contains(strDeviceName)) {
            try {
                MidiDevice device = MidiSystem.getMidiDevice(aInfos[i]);
                boolean bAllowsInput = (device.getMaxTransmitters() != 0);
                boolean bAllowsOutput = (device.getMaxReceivers() != 0);
                if ((bAllowsOutput && bForOutput)
                        || (bAllowsInput && !bForOutput)) {
                    return aInfos[i];
                }
            } catch (MidiUnavailableException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}
项目:uosl    文件:SoundManager.java   
private Sequence[] loadSongs() {
    if(sequencer == null) {
        return null;
    }

    for(int i = 0; i < songs.length; i++) {
        try {
            Path path = Paths.get(SLData.get().getDataPath(), "MUSIC", String.format("ULTIMA%02d.MID", i));
            songs[i] = MidiSystem.getSequence(path.toFile());
        } catch (Exception e) {
            continue;
        }
    }

    return new Sequence[0];
}
项目:MIDI-Automator    文件:MidiUtils.java   
/**
 * Retrieve a MidiDevice.Info for a given name.
 * 
 * This method tries to return a MidiDevice.Info whose name matches the
 * passed name. If no matching MidiDevice.Info is found, null is returned.
 * If bForOutput is true, then only output devices are searched, otherwise
 * only input devices.
 * 
 * @param strDeviceName
 *            the name of the device for which an info object should be
 *            retrieved.
 * @param bForOutput
 *            If true, only output devices are considered. If false, only
 *            input devices are considered.
 * @return A MidiDevice.Info object matching the passed device name or null
 *         if none could be found.
 */
public static MidiDevice.Info getMidiDeviceInfo(String strDeviceName,
        boolean bForOutput) {

    MidiDevice.Info[] aInfos = MidiSystem.getMidiDeviceInfo();

    for (int i = 0; i < aInfos.length; i++) {

        if (aInfos[i].getName().equals(strDeviceName)) {

            try {
                MidiDevice device = MidiSystem.getMidiDevice(aInfos[i]);
                boolean bAllowsInput = (device.getMaxTransmitters() != 0);
                boolean bAllowsOutput = (device.getMaxReceivers() != 0);
                if ((bAllowsOutput && bForOutput)
                        || (bAllowsInput && !bForOutput)) {
                    return aInfos[i];
                }

            } catch (MidiUnavailableException e) {
                // TODO:
            }
        }
    }
    return null;
}
项目:MIDI-Automator    文件:MidiUtils.java   
/**
 * Gets a midi device by name
 * 
 * @param midiDeviceName
 *            The name of the midi device
 * @param outputDevice
 *            "OUT" only output devices are considered, "IN" only input
 *            devices are considered.
 * @return The midi device
 * @throws MidiUnavailableException
 *             If the midi device can not be found
 */
public static MidiDevice getMidiDevice(String midiDeviceName,
        String direction) throws MidiUnavailableException {

    MidiDevice.Info[] midiInfos;
    MidiDevice device = null;

    if (midiDeviceName != null) {

        midiInfos = MidiSystem.getMidiDeviceInfo();

        for (int i = 0; i < midiInfos.length; i++) {
            if (midiInfos[i].getName().equals(midiDeviceName)) {
                device = MidiSystem.getMidiDevice(midiInfos[i]);

                if (getDirectionOfMidiDevice(device).equals(direction)) {
                    return device;
                }
            }
        }

    }
    throw new MidiUnavailableException();
}
项目:KillTheNerd    文件:DesktopMidiPlayer.java   
public DesktopMidiPlayer() throws MidiUnavailableException, IOException, InvalidMidiDataException {
    // Obtains the default Sequencer connected to a default device.
    Sequencer sequencer = MidiSystem.getSequencer();
    // Opens the device, indicating that it should now acquire any
    // system resources it requires and become operational.
    sequencer.open();
    // create a stream from a file
    // FileHandle fh = Gdx.files.internal(Constants.MUSIC);
    // InputStream is = new BufferedInputStream(new FileInputStream(fh.file()));
    InputStream is = new BufferedInputStream(new FileInputStream(new File(Constants.MUSIC2)));
    // Sets the current sequence on which the sequencer operates.
    // The stream must point to MIDI file data.
    sequencer.setSequence(is);
    // Starts playback of the MIDI data in the currently loaded sequence.
    sequencer.start();
    /*try {
        this.sequencer = MidiSystem.getSequencer();
    } catch (MidiUnavailableException e) {
        // Log.error("Error opening midi device.", e);
    }*/

}
项目:K-Visions    文件:MidiHandler.java   
public static void listenStart(){
        close();
        openedDevices.clear();
        MidiDevice device;
        MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo();
        for (int i = 0; i < infos.length; i++) {
            try {
                device = MidiSystem.getMidiDevice(infos[i]);
                System.out.println(infos[i] +" -- "+ infos[i].getDescription());
                java.util.List<Transmitter> transmitters = device.getTransmitters();
                for(int j = 0; j<transmitters.size();j++) {
                    transmitters.get(j).setReceiver(receiver);
                }

                Transmitter trans = device.getTransmitter();
                trans.setReceiver(receiver);

                device.open();
                openedDevices.add(device);
                System.out.println(device.getDeviceInfo()+" Was Opened");
            } catch (MidiUnavailableException e) {
//              e.printStackTrace();
            }
        }
    }
项目:haogrgr-projects    文件:ActorDemo.java   
public void setupMidi() throws Exception {
    synthesizer = MidiSystem.getSynthesizer();
    synthesizer.open();
    midiChannels = synthesizer.getChannels();
    sequencer = MidiSystem.getSequencer();
    sequence = new Sequence(Sequence.PPQ, 10);
    Soundbank sb = synthesizer.getDefaultSoundbank();
    if (sb != null) {
        instruments = synthesizer.getDefaultSoundbank().getInstruments();
        for (int i = 0; i < instruments.length; i++) {
            System.out.printf("%4d: %s%n", i, instruments[i]);
        }
        if (instruments.length > 0) {
            synthesizer.loadInstrument(instruments[0]);
            midiChannels[currentChannel].programChange(0);
        }
        if (instruments.length > 14) {
            synthesizer.loadInstrument(instruments[14]);
            midiChannels[currentChannel].programChange(14);
        }
    }
}
项目:Impro-Visor    文件:MidiSynth.java   
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;
}
项目:Head-First-Java    文件:MiniMusicPlayer3.java   
public void go() {
    setUpGui();

    try {
        Sequencer sequencer = MidiSystem.getSequencer();
        sequencer.open();
        sequencer.addControllerEventListener(ml, new int[] {127});
        Sequence seq = new Sequence(Sequence.PPQ, 4);
        Track track = seq.createTrack();

        int r = 0;
        for (int i = 0; i < 60; i+=4) {
            r = (int) ((Math.random() * 50) + 1);
            track.add(makeEvent(144, 1, r, 100, i));
            track.add(makeEvent(176, 1, 127, 0, i));
            track.add(makeEvent(128, 1, r, 100, i + 2));
        } // end loop

        sequencer.setSequence(seq);
        sequencer.start();
        sequencer.setTempoInBPM(120);
    } catch (Exception ex) {ex.printStackTrace();}
}
项目:Head-First-Java    文件:MiniMusicPlayer2.java   
public void go() {
    try {
        Sequencer sequencer = MidiSystem.getSequencer();
        sequencer.open();

        int[] eventsIWant = {127};
        sequencer.addControllerEventListener(this, eventsIWant);

        Sequence seq = new Sequence(Sequence.PPQ, 4);
        Track track = seq.createTrack();

        for (int i = 5; i < 60; i+= 4) {
            track.add(makeEvent(144, 1, i, 100, i));

            track.add(makeEvent(176, 1, 127, 0, i));

            track.add(makeEvent(128, 1, i, 100, i + 2));
        } // end loop

        sequencer.setSequence(seq);
        sequencer.setTempoInBPM(220);
        sequencer.start();
    } catch (Exception ex) {ex.printStackTrace();}
}
项目:Head-First-Java    文件:MiniMusicPlayer1.java   
public static void main(String[] args) {
    try {
        // make and open a sequencer
        Sequencer sequencer = MidiSystem.getSequencer();
        sequencer.open();

        // make a sequence and a track
        Sequence seq = new Sequence(Sequence.PPQ, 4);
        Track track = seq.createTrack();

        // make a bunch of events to make the notes keep going up
        // (from piano note 5 to piano note 61)
        for (int i = 5; i < 61; i+=4) {
            track.add(makeEvent(144, 1, i, 100, i));
            track.add(makeEvent(128, 1, i, 100, i + 2));
        } // end loop

        sequencer.setSequence(seq);
        sequencer.setTempoInBPM(220);
        sequencer.start();
    } catch (Exception ex) {ex.printStackTrace();}
}
项目:frinika    文件:JVSTSynthMidiDeviceTest.java   
@Test
public void testOpenMidiDevice() throws Exception
{
    FrinikaJVSTSynth synth = (FrinikaJVSTSynth) MidiSystem.getMidiDevice(new FrinikaJVSTSynthProvider.FrinikaJVSTSynthProviderInfo());
    final TargetDataLine line = (TargetDataLine)((Mixer)synth).getLine( new Line.Info(TargetDataLine.class));
    AudioFormat.Encoding PCM_FLOAT = new AudioFormat.Encoding("PCM_FLOAT");
    AudioFormat format = new AudioFormat(PCM_FLOAT, 44100, 32, 2, 4*2, 44100, ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN));
    line.open(format);

    AudioInputStream ais = new AudioInputStream(line);
    assertTrue(AudioSystem.isConversionSupported(Encoding.PCM_SIGNED, ais.getFormat()));

    AudioInputStream convertedAis = AudioSystem.getAudioInputStream(Encoding.PCM_SIGNED, ais);
    SourceDataLine sdl = AudioSystem.getSourceDataLine(convertedAis.getFormat());
    sdl.open();
    sdl.start();
    byte[] buf = new byte[16384];        
    ShortMessage shm = new ShortMessage();
    shm.setMessage(ShortMessage.NOTE_ON, 1, 40, 127);
    synth.getReceiver().send(shm,-1);
    for(int n=0;n<20;n++)
    {
        int read = convertedAis.read(buf);            
        sdl.write(buf, 0, read);
    }        
}