Java MIDI Synthesizer - Can't change instruments

Matt picture Matt · Feb 3, 2011 · Viewed 10.9k times · Source

I can't seem to get the instrument to change. I switch the value of the instrument but get nothing different on the output. I can only get a piano instrument to play no matter what value I try. Here is the simple code below. Does anyone have any suggestions? Or am I missing a fundamental of the instrument object?

import javax.sound.midi.*;
//import javax.sound.*;

public class Drum {
    static int instrument = 45;
    static int note = 100;
    static int timbre = 0;
    static int force = 100;
    public static void main(String[] args) {        
        Synthesizer synth = null;
        try {
            synth = MidiSystem.getSynthesizer();
            synth.open();
        }
        catch (Exception e) {
            System.out.println(e);
        }
        Soundbank soundbank = synth.getDefaultSoundbank();
        Instrument[] instr = soundbank.getInstruments();
        synth.loadInstrument(instr[instrument]);    //Changing this int (instrument) does nothing
        MidiChannel[] mc = synth.getChannels();
        mc[4].noteOn(note, force);
        try { Thread.sleep(1000); } 
        catch(InterruptedException e) {}
        System.out.println(instr[instrument].getName());

        synth.close();

    }
} 

Answer

Matti Virkkunen picture Matti Virkkunen · Feb 3, 2011

You need to tell the channel to use the instrument. I admit I've never used MIDI in Java, but something like mc.programChange(instr.getPatch().getProgram()) sounds promising.