The Notes applet below illustrates the MIDI approach.
A Sequence object is constructed consisting of a Track of MIDI note events.
This is then `played' using the Sequencer object.
Mouse clicks can be used to start and stop the sequencer.
import javax.swing.*; import javax.sound.midi.*; import java.awt.event.*; import java.awt.*; public class Notes extends JApplet implements MouseListener { Sequencer sequencer; int randomPitch() { return((int)(Math.random() * 127)); } public void init() { addMouseListener(this); try { sequencer = MidiSystem.getSequencer(); sequencer.open(); Sequence sequence = new Sequence(Sequence.PPQ, 16); sequencer.setTempoInBPM(120); Track track = sequence.createTrack(); for (int tick = 0; tick < 1000; tick++) { ShortMessage msg = new ShortMessage(); msg.setMessage(ShortMessage.NOTE_ON, 1, randomPitch(), 100); track.add(new MidiEvent(msg, tick)); } sequencer.setSequence(sequence); sequencer.start(); } catch(Exception ex) { ex.printStackTrace(); } } public void mousePressed(MouseEvent event) { if (sequencer.isRunning()) { getContentPane().setBackground(Color.red); sequencer.stop(); } else { getContentPane().setBackground(Color.green); sequencer.start(); } } public void mouseReleased(MouseEvent event) { } public void mouseClicked(MouseEvent event) { } public void mouseEntered(MouseEvent event) { } public void mouseExited(MouseEvent event) { } }
Also see the documentation for the `Sequencer', `Sequence', `MidiSystem' `ShortMessage' and `MidiEvent' classes.