2015-08-09 67 views
1

我在一個程序中工作,當您單擊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(); 
    } 
} 
} 
+2

將mp3嵌入到應用程序中(允許它被包含在Jar文件中),然後簡單地使用'Class#getResource'或'Class#getResourceAsStream'來獲得對它的引用 – MadProgrammer

+0

你是否試圖在jar或在您的IDE? – durron597

+0

*「不斷收到錯誤..」* ..什麼錯誤?始終複製/粘貼錯誤和異常輸出! 'Player player = new Player(bis);''什麼是'Player'?我沒有在Java 8文檔中看到它。爲了更快地獲得更好的幫助,請發佈[MCVE]或[簡短自包含正確示例](http://www.sscce.org/)(包括導入)。 –

回答

1

在所有的興奮,差點忘了來回答這個問題:

如何發揮兩者的應用程序和應用程序內的MP3文件?

首先,使用URL訪問資源與Applet和應用程序兼容。該URL可以從Class.getResource(String)獲得。有關使用該方法的更多詳細信息,請參閱embedded resource info. page

至於播放我們擁有網址的MP3,請參閱Java Sound info. page的MP3解碼支持部分。基本上,它歸結爲將MP3 SPI添加到應用程序的運行時類路徑。

另請注意,該頁面中提到的Clip便利類(在本例中顯示)不適用於大文件。從內存中,它將保存至多1秒的CD質量(立體聲,16位,44.1KHz)聲音。對於較大的文件,您可以直接使用AudioInputStream,讀取字節並將它們反饋回播放它們的聲音API。要麼是這樣,要麼使用BigClip,它將整個流字節緩存在內存中,非常類似Clip