[英]How do I play an mp3 file for both an application and applet?
我正在開發一個程序,當您在applet和應用程序中單擊一個按鈕時,它們都可以發出聲音,但是在該程序的應用程序部分我一直收到錯誤消息。
這是我得到的錯誤: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文件?
首先,使用URL訪問資源與applet和應用程序兼容。 可以從Class.getResource(String)
獲得URL。 有關使用該方法的更多詳細信息,請參見嵌入式資源信息。 頁面 。
關於播放我們擁有URL的MP3,請參閱Java Sound信息的MP3解碼支持部分。 頁面 。 基本上可以歸結為將MP3 SPI添加到應用程序的運行時類路徑。
另請注意,該頁面中提到的Clip
便利類(如示例所示)不適用於大文件。 從內存中,它將最多保留1秒鍾的CD質量(立體聲,16位,44.1 KHz)聲音。 對於較大的文件,您可以直接使用AudioInputStream
,讀取字節並將其反饋給播放它們的聲音API。 要么使用BigClip
,要么將整個流字節緩存在內存中,就像Clip
一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.