我在一個程序中工作,當您單擊applet中和應用程序中的按鈕時,它們都會播放聲音,但在程序的應用程序部分中,我仍然收到錯誤。如何爲應用程序和applet播放mp3文件?
這是我得到的錯誤:sample.mp3(系統找不到指定的文件) 但我清楚地知道它在我的項目中。
public class project extends JApplet {
public void init() {
add(new AppletOrApplicationMainComponent());
}
public static void main(String args[]) {
JFrame frame = new JFrame("");
frame.getContentPane().add(new AppletOrApplicationMainComponent());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
class AppletOrApplicationMainComponent extends JPanel {
public AppletOrApplicationMainComponent() {
super(new BorderLayout());
JButton button = new JButton("Play");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Play();
}
});
add(button, BorderLayout.SOUTH);
}
private void Play(){
try{
File file = new File("sample.mp3");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
Player player = new Player(bis);
player.play();
}catch(Exception e){
e.printStackTrace();
}
}
}
將mp3嵌入到應用程序中(允許它被包含在Jar文件中),然後簡單地使用'Class#getResource'或'Class#getResourceAsStream'來獲得對它的引用 – MadProgrammer
你是否試圖在jar或在您的IDE? – durron597
*「不斷收到錯誤..」* ..什麼錯誤?始終複製/粘貼錯誤和異常輸出! 'Player player = new Player(bis);''什麼是'Player'?我沒有在Java 8文檔中看到它。爲了更快地獲得更好的幫助,請發佈[MCVE]或[簡短自包含正確示例](http://www.sscce.org/)(包括導入)。 –