Marcus Becker
Marcus Becker

Reputation: 352

I can close an AudioInputStream after load the Clip object?

In my code, I'm loading the sound and closing or not closing the AudioInputStream, the sound is played. Is it best to close or is it a problem?

        try {
        as = AudioSystem.getAudioInputStream(new File("som/trippygaia1.mid"));
        clip = AudioSystem.getClip();
        clip.open(as);

        as.close(); // ?

    } catch (Exception e) {
        e.printStackTrace();
    }

    if (clip != null) {
        clip.start();
    }

Upvotes: 1

Views: 790

Answers (3)

train1855
train1855

Reputation: 300

I just checked this in a short test program. The AudioInputStream does not need to stay open in order for the Clip to be able to play back its audio. Incidentally, this also means that the AudioInputStream (but not the Clip) can be loaded using a try-with-resources.

Upvotes: 1

Phil Freihofner
Phil Freihofner

Reputation: 7910

I don't recall if the AudioInputStream itself needs to be closed when you are done loading the audio data to the Clip. I think the AudioInputStream puts some sort of lock on the resource file that you might want to release. The examples I have seen of Java Clip usage don't include a command to close the AudioInputStream. But it shouldn't hurt to close it, once the Clip has been built, afaik.

I look forward to a correction if this turns out to be misinformed.

Upvotes: 0

Noah
Noah

Reputation: 1966

According to the documentation for Clip open:

Says:

Opens the clip, meaning that it should acquire any required system resources and become operational... Note that some lines, once closed, cannot be reopened. Attempts to reopen such a line will always result in a LineUnavailableException.

Clip is a line, so its referring to the clip object and not the stream object.

That said, its probably poor practice to close a stream you just opened in a clip. To properly close the stream, make sure to call the clip's close method, which states:

Closes the line, indicating that any system resources in use by the line can be released..

Upvotes: 0

Related Questions