This demo extends the random melody demo such that notes are constrained to the C major scale.
To hear the result play the midi file below.
View source
Music in western culture is usually organised around regular patterns or within limited boundaries. One of common constraint is the restricting of pitches to particular modes, the most common of which are Major and Minor. In this example notes are generated at random and then checked to see if they are notes in the C major scale (white notes on the piano). If the generated pitch is within the constraints it is added to the melody. This process is repeated until 24 notes pass the test and are added to the phrase.
Charles Dodge and Thomas Jerse discuss the constraining of stochastic methods in music composition in chapter 11 of "Computer Music" (2nd Ed. 1997, Schirmer Books). They deal with statistical constraints while this demo deals with constraints based on music theory.
Lets have a closer look.
23 import jm.JMC; 24 import jm.music.data.*; 25 import jm.midi.*; 26 import jm.util.*;
34 public final class ModeMelody implements JMC { 35 public static void main(String[] args){ 36 Score modeScore = new Score("Mode Melody"); 37 Part inst = new Part("Guitar", SGUITAR, 0); 38 Phrase phr = new Phrase(); 39 int temp; //variable to store random number 40 int[] mode = {0,2,4,5,7,9,11,12}; //C major scale degrees
A variable called 'temp' is declared which will store the temporary random number while it is checked to see if it is within the constraints. An array called 'mode' is declared which holds the semitone steps of the degrees of the major scale - 0 being C.
42 // create a phrase of 32 randomly pitched quavers within C major. 43 for(short i=0;i<32;){ 44 // generate a random number between 30 and 85 // (avoids excessively high and low notes). 45 temp = (int)(Math.random()*55 + 30); 46 //check that it is a note in the mode (C major scale) 47 for (short j=0; j< mode.length; j++) { 48 if ( temp%12 == mode[j]) { 49 // if it is then add it to the phrase and move // to the next note in the phrase 50 Note note = new Note(temp, Q); 51 phr.addNote(note); 52 i++;// only move onto the next note when // a valid pitch is found. 53 } 54 } 55 }
58 inst.addPhrase(phr); 59 modeScore.addPart(inst);
62 Write.midi(modeScore, "modeMelody.mid"); 63 } 64 }
As an exercise you might try to constrain notes to a minor mode, or to limit notes to a smaller range than the full 127 notes.