2017-06-15 109 views
0

我有以下代碼,我創建了一個Sequencer,給它一個Sequence,給Sequence創建一個新的Track,將MidiEvents寫入Track,然後嘗試播放S​​equence當我調用sequencer.start()。我究竟做錯了什麼?無法使用java.midi.sequencer播放聲音

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()); 
    } 
} 

回答

0
  1. 你並不需要記錄,因爲你明確地定義你想要播放的順序。
  2. 您應該首先創建包含曲目和事件的序列。然後將此序列添加到音序器並啓動音序器。
  3. 此外:要聽到任何需要合成器並將其附加到音序器的內容。

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()); 
} 
}