【问题标题】:Trying to play audio, gives me null尝试播放音频,给我 null
【发布时间】:2016-08-08 07:21:28
【问题描述】:
 public static synchronized void playSound(final String url) {
    new Thread(new Runnable() {
        // The wrapper thread is unnecessary, unless it blocks on the
        // Clip finishing; see comments.
        public void run() {
            try {
                Clip clip = AudioSystem.getClip();
                AudioInputStream inputStream = AudioSystem.getAudioInputStream(
                        Main.class.getResourceAsStream("Draco-s-Pong-master\\demo\\Sounds" + url));
                clip.open(inputStream);
                clip.start();
            } catch (Exception e) {
                System.err.println(e.getMessage());
            }
        }
    }).start();
    playSound("Draco Background.wav");
}

我查看了来自其他线程的几十个代码,它们都给我 null 并继续发送垃圾邮件,直到我关闭程序。我在 Sounds 文件夹中有那个 .wav 文件,我什至将它放在项目中的任何地方,它每次仍然给我null。我想要它作为简单的背景。

【问题讨论】:

  • Main.class.getResourceAsStream("Draco-s-Pong-master\\demo\\Sounds" + url)) 更改为 Main.class.getResourceAsStream("//声音" + url))
  • 能不能简单解释一下,我的classpath下的文件夹是什么意思,怎么理解我的classpath?
  • 类路径是文件结构的根目录,默认包的文件夹。见link
  • 我还是不太明白,如何查看我的classpath?

标签: java audio


【解决方案1】:

将您的音频文件(在您的情况下为声音文件夹)移动到您的类文件夹,然后使用更新的路径简单地调用它。作为

Main.class.getResourceAsStream("*PUT YOUR CLASS PATHNAME*\\Sounds" + url))

编辑:

仅使用音频文件的绝对路径。去掉整个 Main.class.getResourceAsStream 并使用

try {
    String fileName = "..add the rest of the absolute path..\\Draco-s-Pong-master\\demo\\Sounds\\Draco Background.wav";
    File file = new File(fileName);
    if (file.exists()) {
        AudioInputStream inputStream = AudioSystem.getAudioInputStream(file);
        Clip clip = AudioSystem.getClip();
        clip.open(inputStream);
        clip.setFramePosition(0); // to start from the beginning
        clip.start();
    } else {
           throw new RuntimeException("Sound: file not found: " + fileName);
    }
} catch(Exception e){
                stopPlay();
                System.err.println(e.printStackTrace());
}

所以现在您将知道问题是否出在给出运行时异常的文件上。否则它在其他地方。

【讨论】:

  • 如何检查我的类路径名是什么我真的不明白?
  • 你的班级所在的目录。
  • 我正在使用 Intelij,C:\Users\Pafo37\Downloads\Draco-s-Pong-master\Draco-s-Pong-master\demo\src\pong 这是我所有的 .java 文件.
  • 应该这样做吗?
  • 仍然为空
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-13
  • 2017-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多