Sends a midi message - Java javax.sound.midi

Java examples for javax.sound.midi:MidiMessage

Description

Sends a midi message

Demo Code

/*//  w w w .j  a  v  a2s.  co  m
 * Copyright (c) 1999 - 2001 by Matthias Pfisterer
 * Copyright (c) 2003 by Florian Bomers
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MetaMessage;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiMessage;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Receiver;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.SysexMessage;
import javax.sound.midi.Transmitter;
import org.apache.log4j.Logger;

public class Main{
    private static final String[] sm_astrKeyNames = { "C", "C#", "D", "D#",
            "E", "F", "F#", "G", "G#", "A", "A#", "B" };
    /**
     * Sends a midi message
     * 
     * @param midiDeviceName
     * @param command
     * @param channel
     * @param controlNo
     * @param value
     * @throws InvalidMidiDataException
     * @throws MidiUnavailableException
     */
    public static void sendMidiMessage(String midiDeviceName, int command,
            int channel, int controlNo, int value)
            throws InvalidMidiDataException, MidiUnavailableException {
        ShortMessage message = new ShortMessage();

        message.setMessage(command, channel - 1, controlNo, value);
        MidiDevice device = MidiUtils.getMidiDevice(midiDeviceName, "OUT");
        device.open();
        long timeStamp = device.getMicrosecondPosition();
        device.getReceiver().send(message, timeStamp);
        device.close();
    }
    /**
     * Sends a midi message
     * 
     * @param midiDeviceName
     * @param command
     * @param channel
     * @param note
     * @param octave
     * @param velocity
     * @throws InvalidMidiDataException
     * @throws MidiUnavailableException
     */
    public static void sendMidiMessage(String midiDeviceName, int command,
            int channel, String note, int octave, int velocity)
            throws InvalidMidiDataException, MidiUnavailableException {
        sendMidiMessage(midiDeviceName, command, channel,
                getKeyNumber(note, octave), velocity);
    }
    /**
     * 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();
    }
    /**
     * Gets the byte value for a key name and a octave
     * 
     * @param note
     *            The key name
     * @param octave
     *            The octave
     * @return The byte value, -1 if no key was found
     */
    private static int getKeyNumber(String note, int octave) {

        int nOctave = (octave + 2) * 12;

        int nNote = -1;
        for (int i = 0; i < sm_astrKeyNames.length; i++) {
            if (sm_astrKeyNames[i].equals(note)) {
                nNote = i;
                break;
            }
        }

        if (nNote == -1) {
            return -1;
        }

        return nOctave + nNote;
    }
    /**
     * 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;
    }
    /**
     * Returns the allowed direction of the given midi device
     * 
     * @param device
     *            The midi device
     * @return "IN" for inbound devices, "OUT" for outbound devices, else <NULL>
     */
    public static String getDirectionOfMidiDevice(MidiDevice device) {

        if (device.getMaxTransmitters() != 0) {
            return "IN";
        }

        if (device.getMaxReceivers() != 0) {
            return "OUT";
        }
        return null;
    }
}

Related Tutorials