Java 尝试播放音频时,显示为空
我从其他线程中查找了几十个代码,它们都给了我空值,并一直垃圾邮件,直到我关闭程序。我在Sounds文件夹中有.wav文件,我甚至把它放在项目中的任何地方,每次都给我空值。我希望它用于简单的背景。移动音频文件(在您的情况下是sound文件夹)到您的类文件夹,然后简单地用更新的路径调用它。作为Java 尝试播放音频时,显示为空,java,audio,Java,Audio,我从其他线程中查找了几十个代码,它们都给了我空值,并一直垃圾邮件,直到我关闭程序。我在Sounds文件夹中有.wav文件,我甚至把它放在项目中的任何地方,每次都给我空值。我希望它用于简单的背景。移动音频文件(在您的情况下是sound文件夹)到您的类文件夹,然后简单地用更新的路径调用它。作为 public static synchronized void playSound(final String url) { new Thread(new Runnable() { /
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");
}
编辑:
仅使用音频文件的绝对路径。省略整个
Main.class.getResourceAsStream
并使用
Main.class.getResourceAsStream("*PUT YOUR CLASS PATHNAME*\\Sounds" + url))
因此,现在您将知道问题是否出在给出运行时异常的文件上。否则它就在其他地方。Main.class.getResourceAsStream(“Draco-s-Pong-master\\demo\\Sounds”+url”)更改为Main.class.getResourceAsStream(“声音”+url)),你能简单解释一下吗,我的类路径下的文件夹是什么意思,如何理解我的类路径?类路径是文件结构的根,作为默认包的文件夹。看,我仍然不完全明白,如何检查我的类路径?如何检查我的类路径名我真的不明白?那是你的类所在的目录。我正在使用Intelij,C:\Users\Pafo37\Downloads\Draco-s-Pong-master\Draco-s-Pong-master\demo\src\Pong这些都是我的.java文件。应该这样做吗?仍然为空
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());
}