public static Music correctPartsKeys ( Music music ) { //we may have key/clef changes //repeat operation for each voice. Key is for all voices //but clef can change from one voice to another for ( Object o : music . getVoices ( ) ) { Voice voice = ( Voice ) o ; if ( voice . hasObject ( KeySignature . class ) && voice . hasObject ( PartLabel . class ) ) { Hashtable partsKey = new Hashtable ( ) ; KeySignature tuneKey = null ; int size = voice . size ( ) ; int i = 0 ; while ( i < size ) { MusicElement me = ( MusicElement ) voice . elementAt ( i ) ; if ( me instanceof KeySignature ) { tuneKey = ( KeySignature ) me ; } else if ( me instanceof PartLabel ) { PartLabel pl = ( PartLabel ) me ; if ( ( tuneKey != null ) && ( partsKey . get ( pl . getLabel ( ) + "" ) == null ) ) { //first time we see this part, store the key partsKey . put ( pl . getLabel ( ) + "" , tuneKey ) ; } else { //not the first time we see this part //add the key tuneKey = ( KeySignature ) partsKey . get ( pl . getLabel ( ) + "" ) ; if ( i < ( size - 1 ) ) { if ( ! ( voice . elementAt ( i + 1 ) instanceof KeySignature ) ) { //if next element is a key, no need to insert one //just before, next while step it'll be defined as //tuneKey voice . insertElementAt ( tuneKey , i + 1 ) ; i ++ ; size ++ ; } } } } i ++ ; } //end for each element of voice } //end voice has key(s) and part(s) } //end for each voice of music //else nothing to do return music ; }
Be sure each part has it s proper key signature .