Synthesizing a MIDI Sequence
MIDI audio is quite different from sampled audio. Instead of recording samples of an actual audio waveform, MIDI files record a sequence of keystrokes on a real or virtual synthesizer keyboard. MIDI can’t be used to represent voice data, but it is a versatile and compact format for polyphonic electronic music. Many hobbyists transcribe well-known works to MIDI or publish their own compositions as MIDI files. An Internet search will reveal many MIDI samples that you can play with any of the audio player programs we’ve developed previously in this chapter.
The javax.sound.midi
package is useful not only for playback of predefined
MIDI files but also for synthesis or playback of MIDI Sequence
objects. The program in Example
17-5, PlayerPiano
, takes as
input a musical score (defined using a simple grammar) and creates a
Sequence
of MidiEvent
objects. It then either plays that
Sequence
through a Sequencer
object or saves the Sequence
as a MIDI file for playback with
some other sound program.
Invoke PlayerPiano
with the
score as a single quoted argument. You can use the -o
argument to specify a filename to save
the MIDI file to. Without this argument, the score will be played
instead. Use -i
to specify a MIDI
instrument number between 0 and 127. Use -t
to specify the tempo in beats (quarter notes) per minute. The notes to play are indicated using the letters A through G, with b and # for flat and sharp, respectively, and “.” for rests. Notes separated by spaces ...
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.