问题
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