所以我正在播放音频一点,我在这个网站上发现了一个问题,我发现了一些代码,我稍微适应了播放音频,但是当我尝试使用代码时,我得到了 java.lang.OutOfMemoryError。

然后我尝试用两千兆字节的 ram 启动它,它仍然给了我错误,老实说我不知道我的代码是怎么回事如下:

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

public class PlaySoundTest {

public static void main(String[] args){
    playSound("audio.wav");
}

public static synchronized void playSound(final String url){
      new Thread(new Runnable(){
        public void run(){
          try {
            Clip clip = AudioSystem.getClip();
            InputStream bufferedIn = new BufferedInputStream(new FileInputStream(new File(url)));
            AudioInputStream audioSrc = AudioSystem.getAudioInputStream(bufferedIn);
            clip.open(audioSrc);
            clip.start(); 
          }catch (Exception e){
            System.err.println(e.getMessage());
          }
        }
      }).start();
    }
}

整个堆栈跟踪就是这样

Exception in thread "Thread-0" java.lang.OutOfMemoryError: Java heap space
at com.sun.media.sound.DirectAudioDevice$DirectClip.open(DirectAudioDevice.java:1131)
at PlaySoundTest$1.run(PlaySoundTest.java:24)
at java.lang.Thread.run(Thread.java:722)

这真让我感到困惑,因为对我来说这段代码看起来很好。只是为了澄清 audio.wav 的大小是 1.5 MB 所以分配 2 千兆字节这真的不应该是一个问题。

我想也许是内存泄漏,但我想不出原因。

如果有人能对此有所了解,我会很高兴。