Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaX MIDI - Play MIDI file with custom soundfont


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?

like image 296
kalidali Avatar asked Feb 01 '26 13:02

kalidali


2 Answers

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.

like image 144
bogdan Avatar answered Feb 03 '26 04:02

bogdan


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!

like image 32
Timur Baysal Avatar answered Feb 03 '26 03:02

Timur Baysal