1 package SnowMailClient.Synthesizer; 2 3 import javax.sound.midi.ShortMessage ; 4 import javax.sound.midi.Synthesizer ; 5 import javax.sound.midi.Receiver ; 6 import javax.sound.midi.MidiSystem ; 7 import javax.sound.midi.MidiUnavailableException ; 8 import javax.sound.midi.InvalidMidiDataException ; 9 10 12 public final class SynthesizerDemo { 13 private ShortMessage message = new ShortMessage (); 14 private Synthesizer synth; 15 private Receiver receiver; 16 17 public SynthesizerDemo() { 18 try { 19 synth = MidiSystem.getSynthesizer(); 20 synth.open(); 21 receiver = synth.getReceiver(); 22 } catch (MidiUnavailableException e) { 23 e.printStackTrace(); 24 } 25 } 26 27 public void playNote(int note, int duration) { 28 setShortMessage(ShortMessage.NOTE_ON, note); 29 receiver.send(message, -1); 30 try { 31 Thread.sleep(duration); 32 } catch (InterruptedException e) { 33 e.printStackTrace(); 34 } 35 setShortMessage(ShortMessage.NOTE_OFF, note); 36 receiver.send(message, -1); 37 } 38 39 public void setInstrument(int instrument) { 40 synth.getChannels()[0].programChange(instrument); 41 } 42 43 private void setShortMessage( 44 int onOrOff, int note) { 45 try { 46 message.setMessage(onOrOff, 0, note, 70); 47 } catch (InvalidMidiDataException e) { 48 e.printStackTrace(); 49 } 50 } 51 52 public void playOctave(int baseNote) { 53 for (int i = 0; i < 24; i+=2) { 54 playNote(baseNote + i, 50); 55 } 56 } 57 58 public static void main(String [] args) { 59 SynthesizerDemo synth = new SynthesizerDemo(); 60 synth.setInstrument(53); 61 synth.playOctave(60); 63 } 64 65 } | Popular Tags |