【问题标题】:Why is it necessary to close an audio Clip?为什么需要关闭音频剪辑?
【发布时间】:2014-02-04 10:27:35
【问题描述】:
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);
        }
    }

我看过一个有点像这个的问题,但我想我会更具体一点。

所以上面的代码是我放在一个单独的类中的一个方法,当用户点击一个按钮时会调用它。没有 .close() 似乎可以正常工作,但我仍然很确定即使我正在播放的文件非常小,我也应该使用 close() 有一些很好的理由?

播放的声音只是一个 .wav 文件,它是一种非常短的哔声,体积非常小。 另外,如果上面的代码中存在一些您可以指出的缺陷,请指出。

如果这恰好是一个完全重复的问题,我会道歉,我希望你能提供它的链接。

【问题讨论】:

  • 如果不再需要关闭文件句柄,这只是关闭文件句柄的正确方法。
  • Closing Streams in Java的可能重复

标签: java


【解决方案1】:

您需要关闭剪辑以释放它使用的任何资源。如果不这样做,您将泄漏内存并最终崩溃并出现 OutOfMemoryException。

【讨论】:

    【解决方案2】:

    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.
    

    【讨论】:

      【解决方案3】:

      是的,这是重复的,请参见此处:Closing Streams in Java

      主要是:您可能会耗尽资源,例如文件指针、内存等。

      在研究时我发现,Java 7 引入了一些语法糖来使这“更容易”: http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-28
        • 2018-02-01
        • 1970-01-01
        相关资源
        最近更新 更多