Generative Creativity - Lecture 6
Applet sound


Notes applet

Java applets can generate sound in the form of notes played on the host machine's MIDI system, or as synthesized waves played using the host machine's synthesizer.

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.


Notes applet code

  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) { }

  }

Notes applet in action


Summary

The basic approach for MIDI output is

The relevant notes etc. get sent at the specified times.


Exercises


Resources

Google `Java Sound' for a general introduction.

Also see the documentation for the `Sequencer', `Sequence', `MidiSystem' `ShortMessage' and `MidiEvent' classes.


Page created on: Wed Jan 14 11:16:40 GMT 2009
Feedback to Chris Thornton