Example usage for javax.sound.midi ShortMessage NOTE_ON

List of usage examples for javax.sound.midi ShortMessage NOTE_ON

Introduction

In this page you can find the example usage for javax.sound.midi ShortMessage NOTE_ON.

Prototype

int NOTE_ON

To view the source code for javax.sound.midi ShortMessage NOTE_ON.

Click Source Link

Document

Command value for Note On message (0x90, or 144).

Usage

From source file:Main.java

public static void main(String[] args) {
    JFrame frame = new JFrame();
    DrawPanel dp = new DrawPanel();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(dp);//  www . j av a2s .  co  m
    frame.pack();
    frame.setLocationByPlatform(true);
    try {
        Sequence seq = new Sequence(Sequence.PPQ, 4);
        Track track = seq.createTrack();
        for (int i = 0; i < 120; i += 4) {
            int d = (int) Math.abs(new Random().nextGaussian() * 24) + 32;
            track.add(makeEvent(ShortMessage.NOTE_ON, 1, d, 127, i));
            track.add(makeEvent(ShortMessage.CONTROL_CHANGE, 1, 127, 0, i));
            track.add(makeEvent(ShortMessage.NOTE_OFF, 1, d, 127, i));
        }
        Sequencer sequencer = MidiSystem.getSequencer();
        sequencer.open();
        sequencer.setSequence(seq);
        sequencer.addControllerEventListener(dp, new int[] { 127 });
        sequencer.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
    frame.setVisible(true);
}

From source file:PlayerPiano.java

public static void addNote(Track track, int startTick, int tickLength, int key, int velocity)
        throws InvalidMidiDataException {
    ShortMessage on = new ShortMessage();
    on.setMessage(ShortMessage.NOTE_ON, 0, key, velocity);
    ShortMessage off = new ShortMessage();
    off.setMessage(ShortMessage.NOTE_OFF, 0, key, velocity);
    track.add(new MidiEvent(on, startTick));
    track.add(new MidiEvent(off, startTick + tickLength));
}

From source file:at.ofai.music.util.WormFileParseException.java

public Sequence toMIDI(EventList pedal) throws InvalidMidiDataException {
    final int midiTempo = 1000000;
    Sequence s = new Sequence(Sequence.PPQ, 1000);
    Track[] tr = new Track[16];
    tr[0] = s.createTrack();/*from  w  w w  .  j a  v a  2  s.  c om*/
    MetaMessage mm = new MetaMessage();
    byte[] b = new byte[3];
    b[0] = (byte) ((midiTempo >> 16) & 0xFF);
    b[1] = (byte) ((midiTempo >> 8) & 0xFF);
    b[2] = (byte) (midiTempo & 0xFF);
    mm.setMessage(0x51, b, 3);
    tr[0].add(new MidiEvent(mm, 0L));
    for (Event e : l) { // from match or beatTrack file
        if (e.midiCommand == 0) // skip beatTrack file
            break;
        if (tr[e.midiTrack] == null)
            tr[e.midiTrack] = s.createTrack();
        //switch (e.midiCommand) 
        //case ShortMessage.NOTE_ON:
        //case ShortMessage.POLY_PRESSURE:
        //case ShortMessage.CONTROL_CHANGE:
        //case ShortMessage.PROGRAM_CHANGE:
        //case ShortMessage.CHANNEL_PRESSURE:
        //case ShortMessage.PITCH_BEND:
        ShortMessage sm = new ShortMessage();
        sm.setMessage(e.midiCommand, e.midiChannel, e.midiPitch, e.midiVelocity);
        tr[e.midiTrack].add(new MidiEvent(sm, (long) Math.round(1000 * e.keyDown)));
        if (e.midiCommand == ShortMessage.NOTE_ON) {
            sm = new ShortMessage();
            sm.setMessage(ShortMessage.NOTE_OFF, e.midiChannel, e.midiPitch, 0);
            tr[e.midiTrack].add(new MidiEvent(sm, (long) Math.round(1000 * e.keyUp)));
        }
    }
    if (pedal != null) { // from MIDI file
        //      if (t.size() > 0)   // otherwise beatTrack files leave an empty trk
        //         t = s.createTrack();
        for (Event e : pedal.l) {
            if (tr[e.midiTrack] == null)
                tr[e.midiTrack] = s.createTrack();
            ShortMessage sm = new ShortMessage();
            sm.setMessage(e.midiCommand, e.midiChannel, e.midiPitch, e.midiVelocity);
            tr[e.midiTrack].add(new MidiEvent(sm, (long) Math.round(1000 * e.keyDown)));
            if (e.midiCommand == ShortMessage.NOTE_ON) {
                sm = new ShortMessage();
                sm.setMessage(ShortMessage.NOTE_OFF, e.midiChannel, e.midiPitch, e.midiVelocity);
                tr[e.midiTrack].add(new MidiEvent(sm, (long) Math.round(1000 * e.keyUp)));
            }
            //catch (InvalidMidiDataException exception) {}
        }
    }
    return s;
}

From source file:com.rockhoppertech.music.midi.js.MIDIEvent.java

public String toReadableString() {
    StringBuilder sb = new StringBuilder();

    // switch(se.getType()) {
    // case MidiEvent.CHANNEL_VOICE_MESSAGE:

    switch (status & 0xF0) {
    case ShortMessage.NOTE_OFF:
        sb.append("Note Off Key=").append(bytes[0]).append(" Velocity=").append(bytes[1]);
        break;//from w ww.j  a v  a  2  s .c om

    case ShortMessage.NOTE_ON:
        sb.append("Note On Key=").append(bytes[0]).append(" Velocity=").append(bytes[1]);
        break;

    case ShortMessage.POLY_PRESSURE:
        sb.append("Polyphonic key pressure key=").append(bytes[0]).append(" pressure=").append(bytes[1]);
        break;

    case ShortMessage.CONTROL_CHANGE:
        sb.append("Control Change controller=").append(bytes[0]).append(" value=").append(bytes[1]);
        sb.append(" ").append(MIDIControllers.getControllerName((int) bytes[0]));

        break;

    case ShortMessage.PROGRAM_CHANGE:
        sb.append("Program Change program=").append(bytes[0]).append(" name=")
                .append(MIDIGMPatch.getName(bytes[0]));
        break;

    case ShortMessage.CHANNEL_PRESSURE:
        sb.append("Channel Pressure pressure=").append(bytes[0]);
        break;

    case ShortMessage.PITCH_BEND:
        // int val = (this.bytes[0] & 0x7f) | ((this.bytes[1] & 0x7f) << 7);
        // short centered = 0x2000;
        short s14bit;
        s14bit = bytes[1];
        s14bit <<= 7;
        s14bit |= bytes[0];

        sb.append("Pitch Bend one=").append(bytes[0]).append(" two=").append(bytes[1]);
        sb.append(" val=").append(s14bit);
        break;
    default:
        sb.append(" Unhandled=").append(status & 0xF0);
        break;
    }
    sb.append(" Channel=").append(status & 0x0F);
    sb.append(" status=").append(Integer.toHexString(status));

    /*
     * case MidiEvent.CHANNEL_MODE_MESSAGE: printChannelModeMessage(se);
     * break;
     * 
     * case MidiEvent.SYSTEM_COMMON_MESSAGE : System.out.print(" system
     * common message "); break;
     * 
     * case MidiEvent.SYSTEM_REALTIME_MESSAGE : System.out.print(" system
     * realtime message "); break;
     * 
     * default: strMessage = "unknown event: status = " + se.getStatus() +
     * ", byte1 = " + this.bytes[0] + ", byte2 = " + this.bytes[1];
     */
    // System.out.print(sw.toString());
    return sb.toString();

}

From source file:at.ofai.music.util.WormFileParseException.java

public static EventList readMidiFile(String fileName, int skipTrackFlag) {
    EventList list = new EventList();
    Sequence s;/*from   w w w. j  ava 2 s  .  c om*/
    try {
        s = MidiSystem.getSequence(new File(fileName));
    } catch (Exception e) {
        e.printStackTrace();
        return list;
    }
    double midiTempo = 500000;
    double tempoFactor = midiTempo / s.getResolution() / 1000000.0;
    // System.err.println(tempoFactor);
    Event[][] noteOns = new Event[128][16];
    Track[] tracks = s.getTracks();
    for (int t = 0; t < tracks.length; t++, skipTrackFlag >>= 1) {
        if ((skipTrackFlag & 1) == 1)
            continue;
        for (int e = 0; e < tracks[t].size(); e++) {
            MidiEvent me = tracks[t].get(e);
            MidiMessage mm = me.getMessage();
            double time = me.getTick() * tempoFactor;
            byte[] mesg = mm.getMessage();
            int channel = mesg[0] & 0x0F;
            int command = mesg[0] & 0xF0;
            if (command == ShortMessage.NOTE_ON) {
                int pitch = mesg[1] & 0x7F;
                int velocity = mesg[2] & 0x7F;
                if (noteOns[pitch][channel] != null) {
                    if (velocity == 0) { // NOTE_OFF in disguise :(
                        noteOns[pitch][channel].keyUp = time;
                        noteOns[pitch][channel].pedalUp = time;
                        noteOns[pitch][channel] = null;
                    } else
                        System.err.println("Double note on: n=" + pitch + " c=" + channel + " t1="
                                + noteOns[pitch][channel] + " t2=" + time);
                } else {
                    Event n = new Event(time, 0, 0, pitch, velocity, -1, -1, 0, ShortMessage.NOTE_ON, channel,
                            t);
                    noteOns[pitch][channel] = n;
                    list.add(n);
                }
            } else if (command == ShortMessage.NOTE_OFF) {
                int pitch = mesg[1] & 0x7F;
                noteOns[pitch][channel].keyUp = time;
                noteOns[pitch][channel].pedalUp = time;
                noteOns[pitch][channel] = null;
            } else if (command == 0xF0) {
                if ((channel == 0x0F) && (mesg[1] == 0x51)) {
                    midiTempo = (mesg[5] & 0xFF) | ((mesg[4] & 0xFF) << 8) | ((mesg[3] & 0xFF) << 16);
                    tempoFactor = midiTempo / s.getResolution() / 1000000.0;
                    //   System.err.println("Info: Tempo change: " + midiTempo +
                    //                  "  tf=" + tempoFactor);
                }
            } else if (mesg.length > 3) {
                System.err.println("midi message too long: " + mesg.length);
                System.err.println("\tFirst byte: " + mesg[0]);
            } else {
                int b0 = mesg[0] & 0xFF;
                int b1 = -1;
                int b2 = -1;
                if (mesg.length > 1)
                    b1 = mesg[1] & 0xFF;
                if (mesg.length > 2)
                    b2 = mesg[2] & 0xFF;
                list.add(new Event(time, time, -1, b1, b2, -1, -1, 0, b0 & 0xF0, b0 & 0x0F, t));
            }
        }
    }
    for (int pitch = 0; pitch < 128; pitch++)
        for (int channel = 0; channel < 16; channel++)
            if (noteOns[pitch][channel] != null)
                System.err.println("Missing note off: n=" + noteOns[pitch][channel].midiPitch + " t="
                        + noteOns[pitch][channel].keyDown);
    return list;
}

From source file:at.ofai.music.util.WormFileParseException.java

public static EventList readBeatsAsText(String fileName) throws Exception {
    EventList list = new EventList();
    BufferedReader inputFile = new BufferedReader(new FileReader(fileName));
    String s = inputFile.readLine();
    if (s.startsWith("###"))
        return readLabelFile(fileName);
    int beats = 0;
    int pitch = 56;
    int vol = 80;
    int ch = 10;//from  w  ww. j a  va  2  s.  c o  m
    int track = 0;
    int fl = 1;
    while (s != null) {
        int ind = s.indexOf(',');
        if (ind < 0)
            ind = s.indexOf(' ');
        double time = 0;
        if (ind >= 0) {
            String tmp = s.substring(0, ind).trim();
            if (tmp.length() == 0) {
                s = inputFile.readLine();
                continue;
            }
            time = Double.parseDouble(tmp);
            s = s.substring(ind + 1);
        } else {
            String tmp = s.trim();
            if (tmp.length() > 0)
                time = Double.parseDouble(tmp);
            s = inputFile.readLine();
        }
        list.add(new Event(time, time, time, pitch, vol, ++beats, 1.0, fl, ShortMessage.NOTE_ON, ch, track));
    }
    return list;
}

From source file:at.ofai.music.util.WormFileParseException.java

public static EventList readBeatTrackFile(String fileName) throws Exception {
    if (!fileName.endsWith(".tmf")) // || fileName.endsWith(".csv"))
        return readBeatsAsText(fileName);
    else {/*ww  w .j av  a2 s. c  o  m*/
        EventList list = new EventList();
        BufferedReader inputFile = new BufferedReader(new FileReader(fileName));
        Matcher s = new Matcher(inputFile.readLine());
        if (!s.matchString("MFile"))
            throw new BTFileParseException("Header not found");
        s.getInt(); // skip fileType
        int tracks = s.getInt();
        int div = s.getInt();
        int tempo = 500000; // default tempo
        double tf = 1e6 / tempo * div;
        int lineCount = 1;
        int beats = 0;
        for (int track = 0; track < tracks; track++) {
            s.set(inputFile.readLine());
            lineCount++;
            if (!s.matchString("MTrk"))
                throw new BTFileParseException("MTrk not found");
            s.set(inputFile.readLine());
            lineCount++;
            while (!s.matchString("TrkEnd")) {
                double time = s.getInt() / tf;
                s.trimSpace();
                if (s.matchString("Tempo")) {
                    tempo = s.getInt();
                    tf = 1e6 / tempo * div;
                } else if (s.matchString("On")) {
                    s.trimSpace();
                    s.matchString("ch=");
                    int ch = s.getInt();
                    s.trimSpace();
                    if (!s.matchString("n="))
                        s.matchString("note=");
                    int pitch = s.getInt();
                    s.trimSpace();
                    if (!s.matchString("v="))
                        s.matchString("vol=");
                    int vol = s.getInt();
                    s.set(inputFile.readLine());
                    lineCount++;
                    s.getInt();
                    s.trimSpace();
                    s.matchString("Off");
                    s.skip('v');
                    s.matchString("ol");
                    s.matchString("=");
                    int flags = s.getInt();
                    list.add(new Event(time, time, time, pitch, vol, ++beats, 1.0, flags, ShortMessage.NOTE_ON,
                            ch, track));
                } else if (!s.matchString("Meta TrkEnd")) {
                    System.err.println("Unmatched text on line " + lineCount + ": " + s.get());
                }
                s.set(inputFile.readLine());
                lineCount++;
            }
        }
        return list;
    }
}

From source file:at.ofai.music.util.WormFileParseException.java

/** Reads a file containing time,String pairs into an EventList. */
public static EventList readLabelFile(String fileName) throws Exception {
    EventList list = new EventList();
    BufferedReader inputFile = new BufferedReader(new FileReader(fileName));
    Matcher s = new Matcher(inputFile.readLine());
    int prevBar = 0;
    int beats = 0;
    int pitch = 56;
    int vol = 80;
    int ch = 10;/*  ww  w.j  av a  2 s  . c om*/
    int track = 0;
    while (s.hasData()) {
        if (!s.matchString("#")) {
            double time = s.getDouble();
            String label = s.get().trim();
            int colon = label.indexOf(':');
            int beat = 0;
            if (colon < 0)
                colon = label.length();
            else
                beat = Integer.parseInt(label.substring(colon + 1));
            int bar = Integer.parseInt(label.substring(0, colon));
            int flags = WormFile.BEAT;
            if (bar != prevBar) {
                flags |= WormFile.BAR;
                prevBar = bar;
            }
            WormEvent ev = new WormEvent(time, time, time, pitch, vol, ++beats, 1.0, flags,
                    ShortMessage.NOTE_ON, ch, track);
            ev.label = label;
            list.add(ev);
            //            System.out.println(time + " " + label);
        }
        s.set(inputFile.readLine());
    }
    return list;
}

From source file:org.monome.pages.configuration.MonomeConfiguration.java

/**
 * Called every time a MIDI message is received, the messages are passed along to each page.
 * /*w  w  w.j  a  v a 2  s.  c om*/
 * @param message The MIDI message received
 * @param timeStamp The timestamp of the MIDI message
 */
public synchronized void send(MidiDevice device, MidiMessage message, long timeStamp) {
    if (this.useMIDIPageChanging) {
        if (message instanceof ShortMessage) {
            ShortMessage msg = (ShortMessage) message;
            int velocity = msg.getData1();
            if (msg.getCommand() == ShortMessage.NOTE_ON && velocity > 0) {
                int channel = msg.getChannel();
                int note = msg.getData1();

                for (int j = 0; j < this.pageChangeMidiInDevices.length; j++) {
                    if (this.pageChangeMidiInDevices[j] == null) {
                        continue;
                    }
                    if (this.pageChangeMidiInDevices[j].compareTo(device.getDeviceInfo().getName()) == 0) {
                        for (int i = 0; i < this.midiPageChangeRules.size(); i++) {
                            MIDIPageChangeRule mpcr = this.midiPageChangeRules.get(i);
                            if (mpcr.checkNoteRule(note, channel) == true) {
                                int switchToPageIndex = mpcr.getPageIndex();
                                Page page = this.pages.get(switchToPageIndex);
                                this.switchPage(page, switchToPageIndex, true);
                            }
                        }
                    }
                }
            }
            if (msg.getCommand() == ShortMessage.CONTROL_CHANGE) {
                int cc = msg.getData1();
                int ccVal = msg.getData2();
                int channel = msg.getChannel();
                for (int j = 0; j < this.pageChangeMidiInDevices.length; j++) {
                    if (this.pageChangeMidiInDevices[j] == null) {
                        continue;
                    }
                    if (this.pageChangeMidiInDevices[j].compareTo(device.getDeviceInfo().getName()) == 0) {
                        for (int i = 0; i < this.midiPageChangeRules.size(); i++) {
                            MIDIPageChangeRule mpcr = this.midiPageChangeRules.get(i);
                            if (mpcr.checkCCRule(cc, ccVal, channel) == true) {
                                int switchToPageIndex = mpcr.getPageIndex();
                                Page page = this.pages.get(switchToPageIndex);
                                this.switchPage(page, switchToPageIndex, true);
                            }
                        }
                    }
                }
            }
        }
    }
    for (int i = 0; i < this.numPages; i++) {
        for (int j = 0; j < this.midiInDevices[i].length; j++) {
            if (this.midiInDevices[i][j] == null) {
                continue;
            }
            if (this.midiInDevices[i][j].compareTo(device.getDeviceInfo().getName()) == 0) {
                this.pages.get(i).send(message, timeStamp);
            }
        }
    }
}

From source file:org.monome.pages.MIDIKeyboardJulienBPage.java

/**
 * Plays a MIDI note.  0 velocity will send a note off, and > 0 velocity will send a note on.
 * /*www  . ja  v  a  2s  .com*/
 * @param note_num
 * @param velocity
 * @param channel
 */
public void playNote(int note_num, int velocity, int channel) {
    ShortMessage note_out = new ShortMessage();
    try {
        if (velocity == 0) {
            note_out.setMessage(ShortMessage.NOTE_OFF, channel, note_num, velocity);
        } else {
            note_out.setMessage(ShortMessage.NOTE_ON, channel, note_num, velocity);
        }
        for (int i = 0; i < midiReceivers.size(); i++) {
            midiReceivers.get(i).send(note_out, -1);
        }
    } catch (InvalidMidiDataException e) {
        e.printStackTrace();
    }
}