Reputation: 7784
The question may seem really simple. I am working on a game project, so for now I need to implement a sound engine.
I have several audio files to be played. I do it this way:
File file = new File("music.mid");
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
For now I am trying to cache those files to increase performance via HashMap:
private HashMap<String, File> cache = new HashMap(); //name - key & file - res
I check for a file in the hashmap and take it out if it exists and reuse it.
However, audio resources still seem to be downloaded each time I need to play a file. (May be input streams are generated again or so)
And game starts lagging every time.
Could you please show me an appropriate way of caching .mid
files, so they could be quickly accessed and played in an application?
Upvotes: 1
Views: 334
Reputation: 5155
A File
object in Java doesn't actually contain the contents of the file, it is only a handle to the file. In fact, the file isn't read until Clip#open
Most operating systems cache commonly read files to RAM, so in most cases you don't need to do it yourself. If you need more power over the caching, cache the Clip
objects:
The Clip interface represents a special kind of data line whose audio data can be loaded prior to playback, instead of being streamed in real time.
For example, you can place the clips on a HashMap
:
HashMap<String, Clip> clips = new HashMap<String, Clip>();
for (String fileName: fileNames) {
File file = new File(fileName);
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clips.put(fileName, clip);
}
clips.get("music.mid").start();
Upvotes: 1