JMUSIC»Stochastic Java

Stochastic Java

This program demonstrates how to create a random melody within the 4th, 5th, and 6th octave.

import jm.JMC;
import jm.music.data.*;
import jm.midi.*;
import jm.util.*;

/**
 * This short example generates a random melody and writes it to a MIDI file
 * called 'stochy.mid'.  It demonstrates how to map a continuous range of
 * real values to the corresponding discrete notes within a specified range.
 *
 * @author Andrew Brown (modified by Bill Manaris)
 */

public final class Stochastic implements JMC
{
   public static void main(String[] args)
   {
       final double TEMPO = 80;    // the higher, the faster the melody
       final int NUM_NOTES = 32;   // length of melody

       Score stochScore = new Score("Stochastic melody", TEMPO);
       Part inst = new Part("Piano", PIANO, 0);
       Phrase phr = new Phrase(0.0);

       // Specify octave range for sonification
       // (Note: there are 11 MIDI octaves, i.e., 0 to 10
       // see http://www.midimountain.com/midi/midi_note_numbers.html)
       final int LOW_OCTAVE  = 4// start at 4th octave, and extend
       final int NUM_OCTAVES = 3// ...three octaves (i.e., C4..B4, C5..B5, C6..B6)

       // number of distinct notes available for mapping data values
       // (12 notes in an octave)
       final int MAX_NOTES = NUM_OCTAVES * 12;

       // specify range of data values (i.e., min and max)
       Double min = 0.0;   // minimum value in data
       Double max = 0.5;   // maximum value in data

       // create a phrase of NUM_NOTES eigth notes picking a random
       // data values within the specified range.
       for (int i = 0; i < NUM_NOTES; i++)
       {
           // Map a data value from range ['min' to 'max']
           // to the corresponding note

           // get a random data value (within the specified data range)
           Double datum = Math.min(Math.random(), max);

           // map data value to the range of available notes [0 to MAX_NOTES - 1]
           int pitch = (int) ((datum - min) * (MAX_NOTES - 1) / (max - min));

           // shift pitch by specified offset (12 notes in an octave)
           pitch += (LOW_OCTAVE * 12);   

           Note note = new Note(pitch, EN);   // create a note object
           phr.addNote(note);                 // add it to the phrase
       }

       inst.addPhrase(phr);       // add the phrase to an instrument (part)
       stochScore.addPart(inst)// add the instrument to the score

       // create a MIDI file of the score
       Write.midi(stochScore, "stochy.mid");
   }
}