Here's some sample Java code that changes the tonality of a MIDI file by transposing it up or down by a specified number of semitones (which can range from 1 to 12):
import javax.sound.midi.*;
public class MidiTranspose {
// Method to transpose a MIDI track by a specified number of semitones
public static void transpose(Track track, int semitones) throws InvalidMidiDataException {
for (int i=0; i<track.size(); i++) {
MidiEvent event = track.get(i);
MidiMessage message = event.getMessage();
if (message instanceof ShortMessage) {
ShortMessage sm = (ShortMessage) message;
int command = sm.getCommand();
if (command == ShortMessage.NOTE_ON || command == ShortMessage.NOTE_OFF) {
int note = sm.getData1();
if (note >= 0 && note <= 127) {
sm.setMessage(command, sm.getChannel(), note+semitones, sm.getData2());
}
}
}
}
}
// Main method to read in a MIDI file, transpose it, and play it back
public static void main(String[] args) {
try {
// Read in the MIDI file
Sequence sequence = MidiSystem.getSequence(new File("input.mid"));
// Transpose it by a specified number of semitones
int semitones = 5; // Example: transpose up by a perfect fourth (7 semitones) or down by a perfect fifth (-7 semitones)
for (Track track : sequence.getTracks()) {
transpose(track, semitones);
}
// Play back the transposed MIDI file using Java's built-in synthesizer
Synthesizer synthesizer = MidiSystem.getSynthesizer();
synthesizer.open();
MidiChannel[] channels = synthesizer.getChannels();
channels[0].programChange(0); // Example: set instrument to piano (program number 0)
sequencer = MidiSystem.getSequencer();
sequencer.open();
sequencer.setSequence(sequence);
sequencer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
To use this code with your own MIDI file, simply replace 'input.mid' with the file path/name of your MIDI file and adjust the semitones variable to the desired transposition amount (between -12 and +12, inclusive). You can also adjust the program/instrument number with the channels[0].programChange(n) line, where n is the MIDI program number (0-127) for the desired instrument.