Search code examples
javaaudiohashmapclip

Java caching .wav fails


I'm building a piano in Java. I have multiple clips which should be played, and to save RAM, I decided to store them in HashMap for later use. But this fails, it only plays one time, ond one time only. What am Ia doing wrong?

Source:

//imports etc.

HashMap<String, Clip> cache = new HashMap<String, Clip>(); //defined as global variable, before the constructor

public void play(String file) {
    Clip clip = null;
    AudioInputStream audio = null;
    if (cache.containsKey(file)) {
        clip = cache.get(file);
    } else {
        audio = AudioSystem.getAudioStream(getClass().getResource("/res/sounds/" + file + ".wav"));
        clip = AudioSystem.getClip();
        clip.open(audio);
        cache.put(file, clip);
    }
    clip.start();
}

Note: String file is just a name of a .wav, such as "C4", or "F#5". And I repeat once again, this code plays the sound for the first time, but never after.


Solution

  • That's because an AudioClip object plays from the last played frame. This isn't reset by calling start.

    You need to reset it everytime you want to play the clip again.

    if (cache.containsKey(file)) {
        clip = cache.get(file);
        clip.setFramePosition(0);
    }