正如标题所说,我有一个在后台播放MIDI文件的游戏。 这似乎会产生数百万个com.sun.media.sound.ModelSource []实例,占用大量RAM,导致GC延迟峰值并可能清除一些SoftReferences(我不确定它们是否这样做)。 我没有任何其他声音相关的代码,它似乎也没有与我使用的音库大小相关。 有没有办法改善内存占用?
我的代码:
public class MusicPlayer {
private Sequencer player;
private Synthesizer synth;
private Soundbank bank;
private boolean paused = false;
private boolean ready = false;
public MusicPlayer() {
try {
// Initialize MIDI output
player = MidiSystem.getSequencer(false);
synth = MidiSystem.getSynthesizer();
bank = MidiSystem.getSoundbank(new BufferedInputStream(getClass().getResourceAsStream("path/to/soundbank.sf2")));
player.open();
synth.open();
player.getTransmitter().setReceiver(synth.getReceiver());
synth.loadAllInstruments(bank);
} catch (Exception e) {
System.err.println("MUSIC INITIALIZATION ERROR: \n" + e.toString());
}
}
/**
* Starts playing a new track
*/
public void play(String name) {
try {
Sequence track = Loader.getSong(name);
player.stop();
player.setSequence(track);
player.setMicrosecondPosition(0); // Rewind if needed
player.setLoopCount(Sequencer.LOOP_CONTINUOUSLY);
paused = false;
ready = true;
player.start(); // And here we go!
} catch (Exception e) {
System.err.println("MUSIC PLAY ERROR: \n" + e.toString());
return;
}
}
/**
* Pauses the currently playing track
*/
public void pause() {
if (!paused && ready) {
player.stop();
paused = true;
}
}
/**
* Unpauses the currently playing track
*/
public void unpause() {
if (paused && ready) {
player.start();
paused = false;
}
}
}