0
public void playClick(String file) 
    {
        try {
        Clip clip = AudioSystem.getClip ();
        AudioInputStream ais = AudioSystem.getAudioInputStream (new File(file));


        clip.open (ais);
        clip.start ();


        }
        catch (Exception e)
        {
            System.out.println(e);
        }
    }

I've seen a question which is kind of like this one but I guess I'll be a bit more specific.

So the code above is a method I put in a separate class to be invoked when the user clicks on a button. It seems to work fine without the .close() but I'm still pretty sure there's got to be some pretty good reason why I should use close() even though the file I'm playing is very small?

The sound played is only a .wav file which is a very short beep sound, of very small size. Also if there are some flaws in the code above that you could point out, please do so.

If this happens to be a completely duplicated question, I'll apologize then and I'm hoping you can provide the link to it.

user3026693
  • 133
  • 2
  • 11
  • It is just proper way to close filehandles if they are no more necessary. – icbytes Feb 04 '14 at 10:31
  • possible duplicate of [Closing Streams in Java](http://stackoverflow.com/questions/515975/closing-streams-in-java) – RossC Feb 04 '14 at 10:40

3 Answers3

0

You need to close the clip to free any resources used by it. If you don't you will leak memory and eventually crash with an OutOfMemoryException.

mikea
  • 6,537
  • 19
  • 36
0

From Sun's documentation for Line:

Closes the line, indicating that any system resources in use 
by the line can be released. If this operation succeeds, 
the line is marked closed and a CLOSE event is dispatched 
to the line's listeners.
Sujith Surendranathan
  • 2,569
  • 17
  • 21
0

Yes it's a duplicate, see here: Closing Streams in Java

Mainly: You can run out of resources, like file-pointers, memory etc.

While researching i found out, that Java 7 introduced some syntactical sugar to make this "easier": http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html

Community
  • 1
  • 1
markusthoemmes
  • 3,080
  • 14
  • 23