2

I'm using the following code to play sound effects in a game of mine:

    try {
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(sound).getAbsoluteFile());
        Clip clip = AudioSystem.getClip();
        clip.open(audioInputStream);
        clip.start();
        clip.loop(Clip.LOOP_CONTINUOUSLY);
    } catch (Exception ex) {
        System.out.println("Error with playing sound.");
        ex.printStackTrace();
    }

This is giving a heap out of space error and linking back to this code. I know I need to do clip.close(), but if I do it right after clip.start() the sound will die instantly and I can't delay since I'm in the main thread. Is there a way to do this without making a new thread for each instance of a sound effect?

Thanks

Nat
  • 890
  • 3
  • 11
  • 23
  • Make sure you execute the code only *once*; most likely you are doing it in some loop creating hundreds of clip instances, eating away your memory. – Durandal Oct 31 '14 at 17:58
  • I need to run it multiple times, every time something happens a sound effect happens with it. Is there a way to schedule the clip instance closure once the clip stops playing? – Nat Oct 31 '14 at 18:00
  • 1
    I think what he means is that you're creating a new instance of it each time you wanna use it. Instead, create one instance, and use it multiple times – Vince Oct 31 '14 at 18:02
  • `clip.loop(Clip.LOOP_CONTINUOUSLY);` I am a little confused. You are talking about closing the Clip but you are shown to be looping it forever. You must be stopping it somewhere. – Radiodef Oct 31 '14 at 18:03
  • Also @user2856410 [see this answer](http://stackoverflow.com/a/25565080/2891664) which shows how to close a Line when it's done. But personally I think the others are right that you have another problem which is you are creating too many Clips. – Radiodef Oct 31 '14 at 18:07
  • Duplicate: http://stackoverflow.com/questions/2792977/do-i-need-to-close-an-audio-clip – Amir Afghani Oct 31 '14 at 18:07
  • Unfortunately, the duplicate listed above has a rather dubious answer. – Phil Freihofner May 01 '18 at 07:14

0 Answers0