Karol.T Karol.T - 7 months ago 19
Java Question

Can't hear any sounds from MIDI

i'm starting with java, and tryin' to play some sounds using midi. I'm following the "Head First" book. The problem is i can't hear any sound, here's my code

package pakedz;
import javax.sound.midi.*;

public class odtwarzaczMuzyki {
public void graj(){
try {
Sequencer sekwenser = MidiSystem.getSequencer();
System.out.println("Mamy sekwenser");
sekwenser.open();

Sequence sekwencja = new Sequence(Sequence.PPQ,4);
Track sciezka = sekwencja.createTrack();

ShortMessage a = new ShortMessage();
a.setMessage(144, 1, 20, 100);
MidiEvent nutaP = new MidiEvent(a, 1);
sciezka.add(nutaP);
ShortMessage b = new ShortMessage();
b.setMessage(128, 1, 44, 100);
MidiEvent nutaK = new MidiEvent(b, 16);
sciezka.add(nutaK);

sekwenser.setSequence(sekwencja);

} catch (Exception ex) {
System.out.println("KUTASMARIAN");
}

};

public static void main (String[] args){
odtwarzaczMuzyki radio = new odtwarzaczMuzyki();
radio.graj();

}

}


i'm using java 8.0

Answer

Need to call the start() method in Sequencer. Below is the modified (untested) code.

Recommend checking the Javadoc and official tutorials.

package pakedz;
import javax.sound.midi.*;

public class odtwarzaczMuzyki {
  public void graj(){
    try {
      Sequencer sekwenser = MidiSystem.getSequencer();
      System.out.println("Mamy sekwenser");
      sekwenser.open();

      Sequence sekwencja = new Sequence(Sequence.PPQ,4);
      Track sciezka = sekwencja.createTrack();

      ShortMessage a = new ShortMessage();
      a.setMessage(144, 1, 20, 100);
      MidiEvent nutaP = new MidiEvent(a, 1);
      sciezka.add(nutaP);
      ShortMessage b = new ShortMessage();
      b.setMessage(128, 1, 44, 100);
      MidiEvent nutaK = new MidiEvent(b, 16);
      sciezka.add(nutaK);

      sekwenser.setSequence(sekwencja);
      sekwenser.start();

    }
    catch (Exception ex) { 
      System.out.println("KUTASMARIAN");
    }
  };

  public static void main (String[] args) {
    odtwarzaczMuzyki radio = new odtwarzaczMuzyki();
    radio.graj();
  }
} 
Comments