Playing MIDI Music with the Java API: Some Simple Examples

Would you like to make music with Java? The Java API comes with a built-in synthesizer for playing notes and chords. Turn on the note(s) you would like, wait for as many milliseconds as you like, then turn the notes off, and repeat. Here's a simple example:

(Download the below file: SynthesizerTest1.java)

import javax.sound.midi.MidiSystem;
import javax.sound.midi.Synthesizer;
import javax.sound.midi.MidiChannel;

public class SynthesizerTest1 {

	public static void main( String[] args ) {

		int channel = 0; // 0 is a piano, 9 is percussion, other channels are for other instruments

		int volume = 80; // between 0 et 127
		int duration = 200; // in milliseconds

		try {
			Synthesizer synth = MidiSystem.getSynthesizer();
			synth.open();
			MidiChannel[] channels = synth.getChannels();

			// --------------------------------------
			// Play a few notes.
			// The two arguments to the noteOn() method are:
			// "MIDI note number" (pitch of the note),
			// and "velocity" (i.e., volume, or intensity).
			// Each of these arguments is between 0 and 127.
			channels[channel].noteOn( 60, volume ); // C note
			Thread.sleep( duration );
			channels[channel].noteOff( 60 );
			channels[channel].noteOn( 62, volume ); // D note
			Thread.sleep( duration );
			channels[channel].noteOff( 62 );
			channels[channel].noteOn( 64, volume ); // E note
			Thread.sleep( duration );
			channels[channel].noteOff( 64 );

			Thread.sleep( 500 );

			// --------------------------------------
			// Play a C major chord.
			channels[channel].noteOn( 60, volume ); // C
			channels[channel].noteOn( 64, volume ); // E
			channels[channel].noteOn( 67, volume ); // G
			Thread.sleep( 3000 );
			channels[channel].allNotesOff();
			Thread.sleep( 500 );



			synth.close();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

}
 
 
 
 
 

A more complete example, that plays scales of notes and percussive instruments, can be downloaded: SynthesizerTest2.java  
 
 
 
 

Finally, here's a small test program that enumerates the MIDI devices on your system:

(Download the below file: ListMidiDevices.java)

import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiDevice.Info;

public class ListMidiDevices {

	public static void main(String[] args) {
		try {
			MidiDevice.Info[] midiDeviceInfoArray = MidiSystem.getMidiDeviceInfo();
			for ( MidiDevice.Info midiDeviceInfo : midiDeviceInfoArray ) {
				System.out.println("Next device:");
				System.out.println("  Name: " + midiDeviceInfo.getName());
				System.out.println("  Description: " + midiDeviceInfo.getDescription());
				System.out.println("  Vendor: " + midiDeviceInfo.getVendor());
				System.out.println("  toString(): " + midiDeviceInfo.toString());
				System.out.println("");
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
}