无法使用java.midi.sequencer

时间:2017-06-15 04:43:32

标签: java javax.sound.midi

我有以下代码,我在其中创建一个Sequencer,给它一个Sequence,给Sequence一个新的Track,将MidiEvents写入Track,然后在我调用sequencer.start()时尝试播放S​​equence。我做错了什么?

public static void main(String args[]) {
    try {

      Sequencer sequencer = MidiSystem.getSequencer();
      sequencer.setTempoInBPM(96);
      sequencer.setTickPosition(0);

      Sequence seq = new Sequence(Sequence.PPQ, 5);

      sequencer.setSequence(seq);

      sequencer.open();

      Track mainTrack = seq.createTrack();
      sequencer.recordEnable(mainTrack, 0);
      sequencer.startRecording();

      ShortMessage msg = new ShortMessage();
      ShortMessage msg2 = new ShortMessage();
      msg.setMessage(ShortMessage.NOTE_ON, 0, 60, 100);
      msg2.setMessage(ShortMessage.NOTE_OFF, 0, 60, 100);
      mainTrack.add(new MidiEvent(msg, 0));s
      mainTrack.add(new MidiEvent(msg2, 400));

      Thread.sleep(5000);

      sequencer.stopRecording();

      sequencer.start();

      Thread.sleep(5000);

      sequencer.close();

    } catch (MidiUnavailableException | InvalidMidiDataException | 
      InterruptedException e) {
      System.err.println(e.getMessage());
    }
}

1 个答案:

答案 0 :(得分:0)

  1. 您无需录制,因为您明确定义了要播放的序列。
  2. 您应首先使用曲目和事件创建序列。然后将此序列添加到序列发生器并启动序列发生器。
  3. 此外:要听到任何声音,您需要合成器并将其连接到音序器。
  4. public static void main(String args[]) {
    try {
    
      Sequencer sequencer = MidiSystem.getSequencer();
      sequencer.setTempoInBPM(96);
      sequencer.setTickPosition(0);
    
      Sequence seq = new Sequence(Sequence.PPQ, 5);
    
      // sequencer.setSequence(seq);
    
      sequencer.open();
    
      Track mainTrack = seq.createTrack();
      // sequencer.recordEnable(mainTrack, 0);
      // sequencer.startRecording();
    
      ShortMessage msg = new ShortMessage();
      ShortMessage msg2 = new ShortMessage();
      msg.setMessage(ShortMessage.NOTE_ON, 0, 60, 100);
      msg2.setMessage(ShortMessage.NOTE_OFF, 0, 60, 100);
      mainTrack.add(new MidiEvent(msg, 0));
      mainTrack.add(new MidiEvent(msg2, 4000));
    
      // Thread.sleep(5000);
      // sequencer.stopRecording();
    
      sequencer.setSequence(seq);
    
      Synthesizer synth = MidiSystem.getSynthesizer();
      sequencer.getTransmitter().setReceiver(synth.getReceiver());
      synth.open();
    
      sequencer.start();
    
      Thread.sleep(5000);
      sequencer.close();
    
    } catch (MidiUnavailableException | InvalidMidiDataException | InterruptedException e) {
      System.err.println(e.getMessage());
    }
    }