JavaX MIDI - Play MIDI file with custom soundfont

1.6k Views Asked by At


I was trying to implement a MIDI player for a java program. So I started using the javax.sound.midi library. I load my Sequencer and my Synthesizer there:

private void playMidiFile() {

   Soundbank soundfont = MidiSystem.getSoundbank(Util.internalFile("FluidR3_GM.sf2").getInputStream());
   Sequencer sequencer = MidiSystem.getSequencer();
   Synthesizer synthesizer = MidiSystem.getSynthesizer();

   sequencer.open();
   synthesizer.open();
   synthesizer.loadAllInstruments(soundfont);

   sequencer.getTransmitter().setReceiver(synthesizer.getReceiver());
   sequencer.setSequence(Util.internalFile("MyMusic.mid").getInputStream());

   sequencer.start();
}

The first second I can clearly hear my loaded soundfont, but after that somehow the midi is played back with a standard soundfont. I checked and the SF2 file is supported by the javax.sound.midi library (synthesizer.isSoundBankSupported(soundfont) returns true).
Does anybody know why my program behaves like this?

2

There are 2 best solutions below

0
On

You may have more transmitters still on your sequencer. I ran into that stupid problem, too. Then I came up with this:

for(Transmitter tm: sequencer.getTransmitters())
{
    tm.close();
}
sequencer.getTransmitter().setReceiver(synthesizer.getReceiver());

I've only just started playing around with Java altogether, let alone Midi. Seems like few people go there to begin with. I wished there were more...

Anyway, it did the trick for me... hope it helps you, too!

0
On

Closing all the transmitters solves the standard font being played, but an easier way to do solve the issue is to create a sequencer without any transmitters:

Sequencer sequencer = MidiSystem.getSequencer(false);

Connecting the custom synthesizer to a sequencer created in this way would only produce the customs sounds.