我試圖製作一個播放聲音的簡單應用程序。我有一個名爲sound.wav的聲音文件位於我的Java項目中(使用eclipse btw)。我不確定如何導航到聲音文件。問題是我不知道如何通過代碼導航到聲音文件。現在我正在運行的是拋出一個空指針異常,即。該文件不存在。這是我到目前爲止的代碼:在Java代碼中查找文件
private static Sound sound;
public static void main(String[] args) {
JFrame j = new JFrame("Sound");
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setSize(300, 150);
sound = new Sound("/Users/Chris/Desktop/Workspace/Sound/sound.wav");
//this is the problem line
JButton play = new JButton("Play");
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sound.play();
}
});
j.add(play,BorderLayout.SOUTH);
j.setVisible(true);
}
這裏是我的聲音類的代碼:
private AudioClip clip;
public Sound(String fileName) {
try {
clip = Applet.newAudioClip(Sound.class.getResource(fileName));
}
catch (Exception e) {
e.printStackTrace();
}
}
public void play() {
try {
new Thread(){
public void run() {
clip.play();
}
}.start();
}
catch (Exception e) {
e.printStackTrace();
}
}
我們不能幫你,直到你告訴我們,*什麼是錯的?* – 2013-02-23 16:31:33
,什麼是你的問題? – Azad 2013-02-23 16:32:01