Because totally random durations make little musical sense to us, this demo adds some certainty of pulse to an uncertain rhythmic outcome. It does this by choosing randomly from a number of four beat rhythms. Because each pattern is itself musically coherent, the result is guaranteed to be reasonable even if highly unpredictable. It is a recombinatorial algorithm, similar to Mozart's Dice Game.
To hear the result play this MIDI file
Lets have a closer look.
Lines 1-4 import useful packages that we need to use in the program. The first import statement gets a standard Java class. The rest of the statements import the jMusic classes.
In this section Score, Part, and Phrase objects are created. As well, arrays of duration are set up, each one 4 beats long. The array called 'pattern' is later used to store one of the randomly selected patterns 0 through 3.
Here one of the four patterns is randomly selected eight times over. Each time the code below is executed before the next pattern is chosen. The switch statement is used with the random number 'x' to select a different outcome in each possible random case.
The case statement consistes of a switch value, in this example the number x, and cases for all possible values of the switch value. case 0, case 1, case 2, etc. This is used in this tutorial code to choose a pattern array depending on a random number allocated to x. The default case is used if all others fail - it is good programming practice to use a default case even if (as in this example) it is considered impossible that the default statement would be required.
Each time a pattern is selected, each rhythmic value in the pattern array is converted into a note on MIDI channel 10 (9 with Java's zero offset) and added to the phrase.
Just for musical coherence a cymbal crash is added to the end of the phrase, otherwise the score does not finish on a down beat.
The phrase is added to a Part and the part to a Score.
As with other jMusic demo files, this code creates a MIDI file from the score. Once created the randomPatterns.mid file can be played by any MIDI file player and will sound correctly using a General MIDI sound source, such as most PC sound cards, or Quicktime. The final line provides feedback during execution that the MIDI file has been successfully written.