Java: OutOfMemoryError when trying to open a 174KB sound file with clip.open()

倾然丶 夕夏残阳落幕 提交于 2019-12-24 12:01:36

问题


I'm simply trying to play a sound clip using the javax.sound.sampled library, using the most basic example I found in the documentation. I've seen a few dozen examples coded exactly this way and they all seem to work, the file is only 174KB so it's not like I'm trying to play an entire concert:

public static void main(String[] args) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
    // TODO Auto-generated method stub
    Clip clip;
    AudioInputStream sound = AudioSystem.getAudioInputStream(new File("test.wav"));
    AudioFormat format = sound.getFormat();
    DataLine.Info info = new DataLine.Info(Clip.class, format);
    clip = (Clip)AudioSystem.getLine(info);
    clip.open(sound);
    clip.start();
}

...and this yields the error:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at com.sun.media.sound.DirectAudioDevice$DirectClip.open(DirectAudioDevice.java:1131)
at test.main(test.java:21)

I have literally no clue what is causing this, I've tried increasing the memory limit for the JVM and that didn't help at all. Any help I can get will be greatly appreciated.


回答1:


I just looked into the source from where the exception originated and in this method it is trying to allocate a byte buffer of the size

 audioInputStream.getFrameLength() * audioInputStream.getFormat().getFrameSize()

if audioInputStream.getFrameLength() returns anything else but -1. So maybe your media file returns unusal values for either of these parameters that causes this code to attempt to allocate a extraordinary large block of memory. I'd suggest to check what values you get calculated for your wav file like this:

AudioInputStream sound = AudioSystem.getAudioInputStream(new File("test.wav"));
System.out.println( "frame length: " + sound.getFrameLength() );
System.out.println( "frame size: " + sound.getFormat().getFrameSize() );



回答2:


Add the following to your Java command

-XX:+HeapDumpOnOutOfMemory

and upon getting the OOM, the JVM will generate a binary heap dump that you can use a tool like Eclipse MAT or VisualVM (comes with the JDK). This will show you what data is being retained in the heap.



来源:https://stackoverflow.com/questions/8156848/java-outofmemoryerror-when-trying-to-open-a-174kb-sound-file-with-clip-open

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!