How to clear Audio Clips from memory
I am using an ArrayList to store all of the audio clips in my code.
I honestly don't know too much about audio in Java, so I'm not really sure how to go about
clearing the Clips from memory once they are done playing.
The .flush() and .drain() methods of the DataLine class sound promising, but again, I'm not entirely sure what they do.
This is the code I have so far:
Code:
import java.io.*;
import javax.sound.sampled.*;
import java.util.*;
class SoundEffectArray {
private static ArrayList<Clip> clips = new ArrayList<Clip>();
public static void addSound(String soundFileName) {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundFileName));
clips.add(AudioSystem.getClip());
Clip currClip = clips.get(clips.size() - 1);
currClip.open(audioInputStream);
currClip.start();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
public static void update() {
ArrayList<Integer> cleanup = new ArrayList<Integer>();
for(int i = 0; i < clips.size(); i++) {
Clip currClip = clips.get(i);
if (currClip.getMicrosecondPosition() >= currClip.getMicrosecondLength()) {
cleanup.add(i);
}
}
for(int i = 0; i < cleanup.size(); i++) {
//I want to clear the clip from memory here
clips.remove((int) cleanup.get(i));
}
}
}