Directions: Melodic retrograde and inversion

In this tutorial we will look at how we can use jMusic as a tool to manipulate musical data by playing a melody backwards, and flipping the melody about the initial pitch.

Click here to view source.

Lets have a closer look.
import jm.JMC;
import jm.util.*;
import jm.music.data.*;

The jMusic classes required to support this program are imported. The JMC allows us to use musical terms rather than numbers, and the music.data classes contain the phrase and note classes we will need.

/**
* A short example which generates a melody's retrograde and inversion
*/
public final class Directions implements JMC{ public static void main(String[] args){

The first thing to do is declare the class, call it Directions, and indicate that we will use the JMC.

The class contains just one method, main(), which is declared in the second line above.

		// make the original phrase
Phrase melody = new Phrase("Original"); for(int i=0;i<12;i++){
Note n = new Note(C4+(int)(Math.random()*18), QUAVER);
melody.addNote(n);
}   Score melScore = new Score(); Part melPart = new Part(); melPart.addPhrase(melody); melScore.addPart(melPart); View.show(melScore);

We start by creating a melody of 12 notes using random pitches over an octave and a half. All notes are a quaver (quarter note) in length.

To help us understand the processes better, the melody phrase is displayed on screen using the show() method, the visualising GUI that appears will have a menu from which you can choose to placyback the score or save it as a MIDI file.

		// reverse the phrase
		Phrase backwards = new Phrase("Retrograde");
		for(int i=melody.size();i>0;i--){
		    backwards.addNote(melody.getNote(i-1));
		}
		    
		Score backScore = new Score();
		Part backPart = new Part();
		backPart.addPhrase(backwards);
		backScore.addPart(backPart);
		    
		View.show(backScore, 50,20);

Next, the a phrase is created and all the melody notes are put into it in reverse order. This phrase is also shown in a second GUI window.

		// invert the melody
// Make a copy of the melody
Phrase flip = melody.copy(); flip.setTitle("Inversion"); // get the first pitch int firstNote = flip.getNote(0).getPitch(); for(int i=0; i< flip.size();i++){ // change the pitch to invert each around the first note
flip.getNote(i).setPitch(firstNote -
(melody.getNote(i).getPitch() - firstNote));
}

Score flipScore = new Score();
Part flipPart = new Part();
flipPart.addPhrase(flip);
flipScore.addPart(flipPart);

View.show(flipScore, 100,40);
}
}

The inversion of the melody is a little more involved. Basically, all notes are moved relative to the first note so they are the same number of semitones away but in the opposite direction. That is, note which were higher than the first will be lower and vice versa.

For convenience there is a Mod method for retrograde and inversion. Check the docs for details.

Try adding a phrase which is the retrograde-inversion.



jMusic Tutorial Index