Getting midi messages from Receiver in Java

前端 未结 1 837
清歌不尽
清歌不尽 2021-01-26 16:38

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 t

相关标签:
1条回答
  • 2021-01-26 17:16

    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() {
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题