简体   繁体   中英

Getting midi messages from Receiver in Java

I am trying to use a receiver so that I can extract midi event information as it is playing. I want to listen for notes played and synchronise them was some event. I have read the documentation and I am not sure how to actually use the transmitter / receiver. If someone could help point me in the right direction on how I can grab midi events from the receiver I would be very grateful.

Edit: The possible duplicate offered below doesn't explain how the receiver actually works. It offers source code on the implementation but as a beginner the source code was too advanced for me to make sense of.

import javax.sound.midi.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public class Main {

    public static Sequencer sequencer;
    public static Sequence sequence;
    public static Receiver synthRcvr;
    public static Transmitter seqTrans;

    public static void main(String[] args) {

        try {
            sequencer = MidiSystem.getSequencer();
            sequence = MidiSystem.getSequence(new File("test.midi"));

            seqTrans = sequencer.getTransmitter();
            synthRcvr = sequencer.getReceiver();
            seqTrans.setReceiver(synthRcvr);

            sequencer.open(); 
            sequencer.setSequence(sequence);

            sequencer.start();
        } catch (IOException | MidiUnavailableException | InvalidMidiDataException e) {
            System.out.println(e);
        }
    }

This was the solution for listening to all midi messages.

import javax.sound.midi.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public class Main {

public static Receiver synthRcvr = new CustomReceiver();
public static Transmitter seqTrans;
public static Synthesizer synth;

public static void main(String[] args) {

    try {
        sequencer = MidiSystem.getSequencer();
        sequence = MidiSystem.getSequence(new File("test.midi"));

        Sequencer sequencer = MidiSystem.getSequencer();
        seqTrans = sequencer.getTransmitter();
        seqTrans.setReceiver(synthRcvr);

        sequencer.open(); 
        sequencer.setSequence(sequence);

        sequencer.start();
    } catch (IOException | MidiUnavailableException | InvalidMidiDataException e) {
        System.out.println(e);
    }
}

This is the class the implements the receiver:

import javax.sound.midi.MidiMessage;
import javax.sound.midi.Receiver;

public class CustomReceiver implements Receiver {

    public CustomReceiver() {

    }

    @Override
    public void send(MidiMessage message, long timeStamp) {
        // Process midi messages here
    }

    @Override
    public void close() {

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM