Java Code Examples for javax.sound.midi.Sequence#PPQ

The following examples show how to use javax.sound.midi.Sequence#PPQ . 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: RealTimeSequencer.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private long millis2tick(long millis) {
    if (divisionType != Sequence.PPQ) {
        double dTick = ((((double) millis) * tempoFactor)
                        * ((double) divisionType)
                        * ((double) resolution))
            / ((double) 1000);
        return (long) dTick;
    }
    return MidiUtils.microsec2ticks(millis * 1000,
                                    currTempo * inverseTempoFactor,
                                    resolution);
}
 
Example 2
Source File: RealTimeSequencer.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private long tick2millis(long tick) {
    if (divisionType != Sequence.PPQ) {
        double dMillis = ((((double) tick) * 1000) /
                          (tempoFactor * ((double) divisionType) * ((double) resolution)));
        return (long) dMillis;
    }
    return MidiUtils.ticks2microsec(tick,
                                    currTempo * inverseTempoFactor,
                                    resolution) / 1000;
}
 
Example 3
Source File: RealTimeSequencer.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private long millis2tick(long millis) {
    if (divisionType != Sequence.PPQ) {
        double dTick = ((((double) millis) * tempoFactor)
                        * ((double) divisionType)
                        * ((double) resolution))
            / ((double) 1000);
        return (long) dTick;
    }
    return MidiUtils.microsec2ticks(millis * 1000,
                                    currTempo * inverseTempoFactor,
                                    resolution);
}
 
Example 4
Source File: RealTimeSequencer.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private long tick2millis(long tick) {
    if (divisionType != Sequence.PPQ) {
        double dMillis = ((((double) tick) * 1000) /
                          (tempoFactor * ((double) divisionType) * ((double) resolution)));
        return (long) dMillis;
    }
    return MidiUtils.ticks2microsec(tick,
                                    currTempo * inverseTempoFactor,
                                    resolution) / 1000;
}
 
Example 5
Source File: TrackAddSameTick.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String argv[]) throws Exception {
    Sequence seq = new Sequence(Sequence.PPQ, 240);
    Track t = seq.createTrack();

    log("add 10 events in random order");
    t.add(createEvent(10, 5));
    t.add(createEvent(0, 0));
    t.add(createEvent(10, 6));
    t.add(createEvent(11, 8));
    t.add(createEvent(10, 7));
    t.add(createEvent(0, 1));
    t.add(createEvent(0, 2));
    t.add(createEvent(15, 9));
    t.add(createEvent(0, 3));
    t.add(createEvent(1, 4));

    // now compare the events.
    // The note param will tell us the
    // the expected position
    long lastTick = 0;
    for (int i = 0; i < t.size(); i++) {
        MidiEvent ev = t.get(i);
        if (ev.getMessage() instanceof ShortMessage) {
            ShortMessage msg = (ShortMessage) ev.getMessage();
            log(""+i+": ShortMessage at tick "+ev.getTick()
                +" with expected position "+msg.getData1());
            if (ev.getTick() < lastTick) {
                log("  FAILED: last tick is larger than this event's tick!");
                failed = true;
            }
            if (i != msg.getData1()) {
                log("  FAILED: Track did not order correctly.");
                failed = true;
            }
        }
    }

    if (failed) throw new Exception("Test FAILED!");
    log("Test passed.");
}
 
Example 6
Source File: MetaCallback.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
MetaCallback() throws Exception {

        sequencer=MidiSystem.getSequencer();
        sequence=new Sequence(Sequence.PPQ,240);
        track=sequence.createTrack();
        sequencer.addMetaEventListener(this);

        byte[] data = new byte[1];

        track.add(new MidiEvent(MidiMsg3(ShortMessage.NOTE_ON+0,45,100),0));
        track.add(new MidiEvent(MidiMsg3(ShortMessage.NOTE_ON+0,45,0),0 + 240));
        int c;
        for(c=0; c < TOTAL_COUNT; c++) {
            data[0]=(byte)(c+1);
            MetaMessage meta = new MetaMessage();
            meta.setMessage(1, data, 1); // type, data, length
            track.add(new MidiEvent(meta,c*20));
        }
        track.add(new MidiEvent(MidiMsg3(ShortMessage.NOTE_ON+9,45,100),c*20));
        track.add(new MidiEvent(MidiMsg3(ShortMessage.NOTE_ON+9,45,0),c*20 + 10));

        sequencer.setSlaveSyncMode(Sequencer.SyncMode.INTERNAL_CLOCK);
        sequencer.setMasterSyncMode(Sequencer.SyncMode.INTERNAL_CLOCK);
        sequencer.open();
        sequencer.setSequence(sequence);
        sequencer.setTempoInBPM(100);
        System.out.println("Starting playback...");
        this.start();
        while (!finished && sequencer.getTickPosition() < sequencer.getTickLength()) {
            System.out.println("Tick "+sequencer.getTickPosition()+"...");
            Thread.sleep(1000);
        }
        System.out.println("Stopping playback...");
        this.stop();
        if (metaCount != TOTAL_COUNT) {
            throw new Exception("Expected "+TOTAL_COUNT+" callbacks, but got "+metaCount+"!");
        }
    }
 
Example 7
Source File: MidiSequenceHandlerImpl.java    From tuxguitar with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void init(){
	try {
		this.sequence = new Sequence(Sequence.PPQ,(int)TGDuration.QUARTER_TIME);
		this.midiTracks = new Track[getTracks()];
		for (int i = 0; i < this.midiTracks.length; i++) {
			this.midiTracks[i] = this.sequence.createTrack();
		}
	} catch (InvalidMidiDataException e) {
		e.printStackTrace();
	}
}
 
Example 8
Source File: MidiSequenceBuilder.java    From mpcmaid with GNU Lesser General Public License v2.1 5 votes vote down vote up
public MidiSequenceBuilder(final int ppq) {
	try {
		sequence = new Sequence(Sequence.PPQ, ppq);
	} catch (InvalidMidiDataException e) {
		e.printStackTrace();
	}
}
 
Example 9
Source File: MidiUtils.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
/**
 * Given a tick, convert to microsecond
 * @param cache tempo info and current tempo
 */
public static long tick2microsecond(Sequence seq, long tick, TempoCache cache) {
    if (seq.getDivisionType() != Sequence.PPQ ) {
        double seconds = ((double)tick / (double)(seq.getDivisionType() * seq.getResolution()));
        return (long) (1000000 * seconds);
    }

    if (cache == null) {
        cache = new TempoCache(seq);
    }

    int resolution = seq.getResolution();

    long[] ticks = cache.ticks;
    int[] tempos = cache.tempos; // in MPQ
    int cacheCount = tempos.length;

    // optimization to not always go through entire list of tempo events
    int snapshotIndex = cache.snapshotIndex;
    int snapshotMicro = cache.snapshotMicro;

    // walk through all tempo changes and add time for the respective blocks
    long us = 0; // microsecond

    if (snapshotIndex <= 0
        || snapshotIndex >= cacheCount
        || ticks[snapshotIndex] > tick) {
        snapshotMicro = 0;
        snapshotIndex = 0;
    }
    if (cacheCount > 0) {
        // this implementation needs a tempo event at tick 0!
        int i = snapshotIndex + 1;
        while (i < cacheCount && ticks[i] <= tick) {
            snapshotMicro += ticks2microsec(ticks[i] - ticks[i - 1], tempos[i - 1], resolution);
            snapshotIndex = i;
            i++;
        }
        us = snapshotMicro
            + ticks2microsec(tick - ticks[snapshotIndex],
                             tempos[snapshotIndex],
                             resolution);
    }
    cache.snapshotIndex = snapshotIndex;
    cache.snapshotMicro = snapshotMicro;
    return us;
}
 
Example 10
Source File: MidiUtils.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Given a tick, convert to microsecond
 * @param cache tempo info and current tempo
 */
public static long tick2microsecond(Sequence seq, long tick, TempoCache cache) {
    if (seq.getDivisionType() != Sequence.PPQ ) {
        double seconds = ((double)tick / (double)(seq.getDivisionType() * seq.getResolution()));
        return (long) (1000000 * seconds);
    }

    if (cache == null) {
        cache = new TempoCache(seq);
    }

    int resolution = seq.getResolution();

    long[] ticks = cache.ticks;
    int[] tempos = cache.tempos; // in MPQ
    int cacheCount = tempos.length;

    // optimization to not always go through entire list of tempo events
    int snapshotIndex = cache.snapshotIndex;
    int snapshotMicro = cache.snapshotMicro;

    // walk through all tempo changes and add time for the respective blocks
    long us = 0; // microsecond

    if (snapshotIndex <= 0
        || snapshotIndex >= cacheCount
        || ticks[snapshotIndex] > tick) {
        snapshotMicro = 0;
        snapshotIndex = 0;
    }
    if (cacheCount > 0) {
        // this implementation needs a tempo event at tick 0!
        int i = snapshotIndex + 1;
        while (i < cacheCount && ticks[i] <= tick) {
            snapshotMicro += ticks2microsec(ticks[i] - ticks[i - 1], tempos[i - 1], resolution);
            snapshotIndex = i;
            i++;
        }
        us = snapshotMicro
            + ticks2microsec(tick - ticks[snapshotIndex],
                             tempos[snapshotIndex],
                             resolution);
    }
    cache.snapshotIndex = snapshotIndex;
    cache.snapshotMicro = snapshotMicro;
    return us;
}
 
Example 11
Source File: SeqRecordDoesNotCopy.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String argv[]) {
    Sequencer s = null;
    try {
        s = MidiSystem.getSequencer();
        s.open();
    } catch (final MidiUnavailableException ignored) {
        // the test is not applicable
        return;
    }
    try {
        Sequence seq = new Sequence(Sequence.PPQ, 384, 2);
        s.setSequence(seq);
        Track t = seq.getTracks()[0];
        ShortMessage msg = new ShortMessage();
        msg.setMessage(0x90, 0x40, 0x7F);
        t.add(new MidiEvent(msg, 11000));
        msg.setMessage(0x90, 0x40, 0x00);
        t.add(new MidiEvent(msg, 12000));
        t = seq.getTracks()[1];
        s.recordEnable(t, -1);
        System.out.println("Started recording...");
        s.startRecording();
        Receiver r = s.getReceiver();
        Thread.sleep(100);
        // send a normal message
        System.out.println("Recording a normal NOTE ON message...");
        msg.setMessage(0x90, 0x40, 0x6F);
        r.send(msg, -1);
        Thread.sleep(100);
        // send a normal message
        System.out.println("Recording a normal NOTE OFF message...");
        msg.setMessage(0x90, 0x40, 0x00);
        r.send(msg, -1);
        Thread.sleep(100);
        s.stop();
        // now see if the messages were recorded
        System.out.println("Recorded messages:");
        int sameMessage = 0;
        for (int i = 0; i < t.size(); i++) {
            System.out.print(" "+(i+1)+". ");
            printEvent(t.get(i));
            if (t.get(i).getMessage() == msg) {
                System.out.println("## Failed: Same Message reference!");
                sameMessage++;
            }
        }
        if (sameMessage > 0) {
            System.out.println("## Failed: The same instance was recorded!");
            throw new Exception("Test FAILED!");
        }
        System.out.println("Did not detect any duplicate messages.");
        System.out.println("Test passed.");
    } catch (Exception e) {
        System.out.println("Unexpected Exception: "+e);
        //e.printStackTrace();
        throw new RuntimeException("Test FAILED!");
    } finally {
        s.close();
    }
}
 
Example 12
Source File: LoopIAE.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] argv) throws Exception {
    if (!hasSequencer()) {
        return;
    }
    Sequencer sequencer = MidiSystem.getSequencer();
    Sequence sequence = new Sequence(Sequence.PPQ, 240);
    Track track = sequence.createTrack();

    track.add(new MidiEvent(MidiMsg3(ShortMessage.NOTE_ON+0,45,100),0));
    track.add(new MidiEvent(MidiMsg3(ShortMessage.NOTE_ON+0,45,0),0 + 240));
    track.add(new MidiEvent(MidiMsg3(ShortMessage.NOTE_ON+9,45,100),10*20));
    track.add(new MidiEvent(MidiMsg3(ShortMessage.NOTE_ON+9,45,0),10*20 + 10));

    try {
        sequencer.open();
        sequencer.setSequence(sequence);
        sequencer.setTempoInBPM(100);

        System.out.println("Setting loop end point to 1");
        sequencer.setLoopEndPoint(1);
        System.out.println("  -> effectively: "+sequencer.getLoopEndPoint());
        System.out.println("Setting loop start point to 2 -- should throw IAE");
        sequencer.setLoopStartPoint(2);
        System.out.println("  -> effectively: "+sequencer.getLoopStartPoint());
        System.out.println("No IllegalArgumentException was thrown!");
        failed = true;
    } catch (IllegalArgumentException iae) {
        System.out.println("IAE was thrown correctly.");
    } catch (MidiUnavailableException mue) {
        System.out.println("MidiUnavailableException was thrown: " + mue);
        System.out.println("Cannot execute test.");
    } catch (InvalidMidiDataException imEx) {
        System.out.println("InvalidMidiDataException was thrown.");
        imEx.printStackTrace();
        System.out.println("Cannot execute test.");
    } finally {
        if (sequencer != null && sequencer.isOpen()) {
            sequencer.close();
        }
    }
    if (failed) {
        throw new Exception("Test FAILED!");
    }
    System.out.println("test passed.");
}
 
Example 13
Source File: Properties.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String argv[]) throws Exception {
    // don't need to catch exceptions: any exception is a
    // failure of this test

    Map<String, Object> p = new HashMap<String,Object>();
    p.put("author", "Florian");
    p.put("duration", new Long(1000));
    p.put("MyProp", "test");

    out("Testing AudioFileFormat properties:");
    // create an AudioFileFormat with properties
    AudioFormat format = new AudioFormat( 44100.0f, 16, 2, true, false);
    AudioFileFormat aff =
        new AudioFileFormat(AudioFileFormat.Type.WAVE,
                            format, 1000, p);
    // test that it has the properties
    boolean failed = compare(p, aff.properties());
    // test getProperty()
    Object o = aff.getProperty("author");
    if (o == null || !o.equals("Florian")) {
        out("  getProperty did not report an existing property!");
        failed = true;
    }
    o = aff.getProperty("does not exist");
    if (o != null) {
        out("  getProperty returned something for a non-existing property!");
        failed = true;
    }
    if (!failed) {
        out("  OK");
    } else {
        g_failed = true;
    }



    out("Testing MidiFileFormat properties:");
    // create a MidiFileFormat with properties
    MidiFileFormat mff =
        new MidiFileFormat(0, Sequence.PPQ, 240,
                           1000, 100, p);
    // test that it has the properties
    failed = compare(p, mff.properties());
    // test getProperty()
    o = mff.getProperty("author");
    if (o == null || !o.equals("Florian")) {
        out("  getProperty did not report an existing property!");
        failed = true;
    }
    o = mff.getProperty("does not exist");
    if (o != null) {
        out("  getProperty returned something for a non-existing property!");
        failed = true;
    }
    if (!failed) {
        out("  OK");
    } else {
        g_failed = true;
    }


    if (g_failed) throw new Exception("Test FAILED!");
    System.out.println("Test passed.");
}
 
Example 14
Source File: Midi2WavRenderer.java    From computoser with GNU Affero General Public License v3.0 4 votes vote down vote up
public static double send(Sequence seq, Receiver recv) {
    float divtype = seq.getDivisionType();
    assert (seq.getDivisionType() == Sequence.PPQ);
    Track[] tracks = seq.getTracks();
    int[] trackspos = new int[tracks.length];
    int mpq = 500000;
    int seqres = seq.getResolution();
    long lasttick = 0;
    long curtime = 0;
    while (true) {
        MidiEvent selevent = null;
        int seltrack = -1;
        for (int i = 0; i < tracks.length; i++) {
            int trackpos = trackspos[i];
            Track track = tracks[i];
            if (trackpos < track.size()) {
                MidiEvent event = track.get(trackpos);
                if (selevent == null || event.getTick() < selevent.getTick()) {
                    selevent = event;
                    seltrack = i;
                }
            }
        }
        if (seltrack == -1)
            break;
        trackspos[seltrack]++;
        long tick = selevent.getTick();
        if (divtype == Sequence.PPQ)
            curtime += ((tick - lasttick) * mpq) / seqres;
        else
            curtime = (long) ((tick * 1000000.0 * divtype) / seqres);
        lasttick = tick;
        MidiMessage msg = selevent.getMessage();
        if (msg instanceof MetaMessage) {
            if (divtype == Sequence.PPQ)
                if (((MetaMessage) msg).getType() == 0x51) {
                    byte[] data = ((MetaMessage) msg).getData();
                    mpq = ((data[0] & 0xff) << 16) | ((data[1] & 0xff) << 8) | (data[2] & 0xff);
                }
        } else {
            if (recv != null)
                recv.send(msg, curtime);
        }
    }

    return curtime / 1000000.0;
}