2013-10-15 68 views
0

我一直在尋找解決這個問題的一些解決方案,但似乎沒有任何幫助。試圖從jar中加載文件時出現問題

我試圖加載一個文件(「soundfile.wav」),所以我可以在我的playSound方法中使用它。我希望它在導出時從jar文件中加載,因此下載時不會看到該文件。

package soundplayer; 

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.sound.sampled.*; 
import javax.swing.*; 

import java.io.*; 

public class SoundPlayer extends JFrame 
{ 
    private static final long serialVersionUID = 1L; 

    public String code = "up up down down left right left right b a"; 
    static SoundPlayer soundPlayer; 

    public static void main(String[] args) 
    { 
     soundPlayer = new SoundPlayer(); 
     soundPlayer.setVisible(true); 
    } 

    public SoundPlayer() 
    { 
     //Look and feel 
     String lookAndFeel = UIManager.getSystemLookAndFeelClassName(); 
     try { 
     UIManager.setLookAndFeel(lookAndFeel); 
     } catch (ClassNotFoundException | InstantiationException| IllegalAccessException | UnsupportedLookAndFeelException e2) {e2.printStackTrace();} 

     //Window Stuff 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setBounds(50, 50, 250, 80); 
     setTitle("Sound Player Test"); 
     getContentPane().setLayout(null); 

     //Components 
     final JTextField typingArea = new JTextField(1); 
     typingArea.setText("up up down down left right left right b a"); 
     typingArea.setBounds(10, 10, 100, 25); 
     getContentPane().add(typingArea); 

     final JLabel label = new JLabel("Now playing: "); 
     label.setBounds(10, 40, 400, 25); 
     label.setVisible(false); 
     getContentPane().add(label); 

     JButton button = new JButton("Check"); 
     button.addActionListener(new ActionListener() 
     { 
      public void actionPerformed(ActionEvent e) 
      { 
       if(typingArea.getText().equals(code)) 
       { 
        setBounds(50, 50, 250, 110); 
        label.setVisible(true); 
        File file = new File("sound.wav"); 
        playSound(file); 
       } 
      } 
     }); 
     button.setBounds(125, 10, 100, 25); 
     getContentPane().add(button); 
    } 

    public static void playSound(File file) 
    { 
     try 
     { 
      Clip clip = AudioSystem.getClip(); 
      clip.open(AudioSystem.getAudioInputStream(file)); 
      clip.start(); 
     } 
     catch (Exception exc) 
     { 
      exc.printStackTrace(System.out); 
     } 
    } 
} 

回答

2

的問題是線

File file = new File("sound.wav"); 

這是直接訪問文件系統。你想要的是從你的JAR中加載資源。 這可以通過使用類加載器來完成:

getClass().getResource("sound.wav"); 

然後,您將有一個資源,其提供的getInputStream一樣,所以你不通過一個文件到playSound,但資源。

相關問題