尝试播放声音时出现错误。由于某种原因,我收到了空指针异常。我同时使用的位置和文件都存在,并且在输出文件字符串时,我确实获得了文件的正确路径。空指针位于.open行上。我究竟做错了什么?
package main;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
public class Sound {
Clip background;
public void init() {
try {
String file = new File("").getAbsolutePath() + "\\Sounds\\Pacman_Opening.wav";
System.out.println(file);
background = AudioSystem.getClip();
background.open(AudioSystem.getAudioInputStream(getClass().getResource(file)));
} catch (LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void playBG() {
background.start();
}
public void stopBG() {
background.stop();
}
public static void main(String[] args) {
Sound s = new Sound();
s.init();
s.playBG();
}
}
这是错误(第一行是位置):
Exception in thread "main" java.lang.NullPointerException
at com.sun.media.sound.WaveFileReader.getAudioInputStream(Unknown Source)
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at main.Sound.init(Sound.java:21)
at main.Sound.main(Sound.java:42)
最佳答案
Class.getResource()
不使用文件名-它使用资源名称。
为什么不直接创建File
并将其传递给getAudioInputStream
?
// TODO: Avoid backslashes in file constructor calls; there are other ways
// of creating relative paths
File file = new File("Sounds\\Pacman_Opening.wav");
...
background.open(AudioSystem.getAudioInputStream(file));