KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > SnowMailClient > Synthesizer > SynthesizerDemo


1 package SnowMailClient.Synthesizer;
2
3 import javax.sound.midi.ShortMessage JavaDoc;
4 import javax.sound.midi.Synthesizer JavaDoc;
5 import javax.sound.midi.Receiver JavaDoc;
6 import javax.sound.midi.MidiSystem JavaDoc;
7 import javax.sound.midi.MidiUnavailableException JavaDoc;
8 import javax.sound.midi.InvalidMidiDataException JavaDoc;
9
10 /** from java sun tech tipps March2004
11 */

12 public final class SynthesizerDemo {
13   private ShortMessage JavaDoc message = new ShortMessage JavaDoc();
14   private Synthesizer JavaDoc synth;
15   private Receiver JavaDoc receiver;
16
17   public SynthesizerDemo() {
18     try {
19       synth = MidiSystem.getSynthesizer();
20       synth.open();
21       receiver = synth.getReceiver();
22     } catch (MidiUnavailableException JavaDoc 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 JavaDoc 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 JavaDoc 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 JavaDoc[] args) {
59     SynthesizerDemo synth = new SynthesizerDemo();
60     synth.setInstrument(53);
61     //can set instrument here
62
synth.playOctave(60);
63   }
64
65 }
Popular Tags