Questions about Clip management

Currently when I load my clips I call this:


Clip clip = (Clip) AudioSystem.getLine(info);
clip.open(audioFormat, audio, 0, size);
clip.stop();
clip.flush();
clip.close();

So that the Clip is loaded into memory and won’t lag before playing the first time I call for it. This works fine on Windows and Linux, but on Mac’s it makes little clicking sounds like it’s playing the beginning of each clip. Is there a better way to do this?

Also, can I reuse Clips? Right now the biggest thing making the allocations build up so that the GC gets called frequently is my use of Clips. I want to be able to hold on to a Clip and tell it to .start() again later or something so that I don’t have to create a new one.

To try this I take that first clip and call:


if (!clip.isOpen()) {
       clip.open(audioFormat, audio, 0, size);
}
clip.start();

However this doesn’t seem to work. If this is possible, what do I need to do to reuse my Clips?

not sure if i understand you right. all you want to do is load some clip and play it multiple times, right?
i do it this way:

public void play() {
if (soundEnabled) {
if (!clip.isRunning()) {
clip.setFramePosition(0); // rewind the clip
clip.start();
}
}
}

// for looping sounds
public void startLoop() {
if (soundEnabled) {
if (clip.isRunning()) {
clip.stop();
}

        clip.setFramePosition(0); // rewind the clip
        clip.loop(Clip.LOOP_CONTINUOUSLY);
    }
}

regarding the click sounds:
i always get them (on my windows machine) when i call close() or flush(). i decided not call them any longer. i load all clips at the startup of the game, keep them in memory, use the above methods to play them and let the environment system do the cleanup when the application exits. this is probably not the best way, but it works best for me.

aaah, sorry for not using the

 tags ... :-/

Thanks for that! I thought that was what I was doing… so I must be missing something :slight_smile: At least I know how to do it right though, thanks!

Everything works great now :slight_smile: