Real-Time MIDI Sounds
Example 17-5 played a
Sequence
of MIDI events through a Sequencer
object. It is also possible to synthesize music by directly
controlling one or more MidiChannel
objects of a Synthesizer
object.
This technique requires you to turn notes on and off in real time; it
is demonstrated in Example
17-6, which turns your computer keyboard into a drum machine.
This program uses MIDI channel 10, which is reserved (by the General
Midi specification) for percussion. When sending notes to this
channel, the different key numbers don’t produce a different pitch,
but instead make different percussive sounds. The Drums
program displays an AWT window that is
used to capture java.awt.event.KeyEvent
objects. Key down
and key up events are translated into noteOn
and noteOff
calls to the MidiChannel
, using the keycode of the key as
the number of the percussion instrument to play. The MIDI standard
defines percussion instruments for notes 35 through 81, inclusive. You
can examine the VK_
constants of
KeyEvent
to determine which keys
produce which codes, or you can just experiment by striking keys at
random!
Note that the program also uses the position of the mouse to control the volume of the percussion sounds. Move the mouse to the right side of the window for louder sounds, and move it to the left for softer sounds. If you don’t hear anything, be sure that it is correctly positioned in the right side of the displayed window.
You may notice a slight delay between the time you strike ...
Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.