2013-02-23 66 views
0

我試圖製作一個播放聲音的簡單應用程序。我有一個名爲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(); 
    } 
} 
+0

我們不能幫你,直到你告訴我們,*什麼是錯的?* – 2013-02-23 16:31:33

+0

,什麼是你的問題? – Azad 2013-02-23 16:32:01

回答

5

Class.getResource(),作爲其javadoc的指示,從classpath讀取資源。不是來自文件系統。

要麼從文件中讀取數據,要使用文件IO(即一個FileInputStream),或者要從類路徑中讀取數據,並且應該使用Class.getResource()並傳遞一個資源路徑,從類路徑。例如,如果sound.wav是在運行時類路徑,在包com.foo.bar.sounds,代碼應該是

Sound.class.getResource("/com/foo/bar/sounds/sound.wav") 
+0

我將如何去獲取文件的資源路徑? – SgtStud 2013-02-23 16:35:14

+0

閱讀我的答案。我完成了它。 – 2013-02-23 16:35:35

+0

完美的作品。非常感激! – SgtStud 2013-02-23 16:37:56