Ok, i’m writing a basic game and decided to use MIDI sounds for the fact that they’re tiny compared to MP3. I also decided to use it since Java hosts it’s own API instead of having to use a third-party include.
However, when i’m running a single MIDI file, which usually is around 7000 bytes, my applications free memory is drained so much that it often can pause/interrupt or even throw an exception.
My implementation is;
private class Track {
private Sequencer sequencer;
private Sequence sequence;
private int id;
private boolean loop;
public Track(final int id, final byte[] buffer, final boolean loop) throws IOException, InvalidMidiDataException, MidiUnavailableException
{
this.id = id;
this.sequence = MidiSystem.getSequence(new ByteArrayInputStream(buffer));
this.sequencer = MidiSystem.getSequencer();
this.loop = loop;
}
public synchronized boolean destroy()
{
this.id = -1;
this.sequencer = null;
this.sequence = null;
this.loop = false;
return this.sequencer == null;
}
public synchronized boolean play() throws InvalidMidiDataException, MidiUnavailableException
{
return play(loop);
}
public synchronized boolean play(boolean loop) throws InvalidMidiDataException, MidiUnavailableException
{
if(sequencer != null && sequencer.isRunning())
sequencer.stop();
sequencer.open();
sequencer.setSequence(sequence);
sequencer.setLoopCount(Integer.MAX_VALUE);
sequencer.start();
return sequencer.isRunning();
}
public synchronized boolean stop()
{
if(sequencer != null && sequencer.isRunning())
sequencer.stop();
return sequencer != null && !sequencer.isRunning();
}
public synchronized boolean playing()
{
return sequencer != null && sequencer.isRunning();
}
}
At the moment I removed everything graphic render related from the application to check that I didn’t have a leak in there, but this was causing the problems.
It’s literally using up over 70MB of Ram just for a 7000 byte file, is that even possible?
To check how much memory is available i’m simply painting;
graphics.drawString("Free: " + Runtime.getRuntime().freeMemory(), 10, 35);
Thanks for any help, will be appreciated.
After looking into it I found out that the ‘close’ method is required to stop memory being used after stopping a synchroniser.