将音乐添加到JFrame的简单方法是什么?我试过这个:
Clip clip = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.getAudioInputStream(new File( "song.mp3") );
clip.open(ais);
clip.loop(Clip.LOOP_CONTINUOUSLY);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// A GUI element to prevent the Clip's daemon Thread
// from terminating at the end of the main()
JOptionPane.showMessageDialog(null, "Close to exit!");
}
});
但它给了我一些sintax错误。
答案 0 :(得分:0)
很难100%肯定,但看起来你似乎忽略了,但你似乎忽略了各种类/方法抛出的异常,因为其余代码似乎工作正常......
try {
Clip clip = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.getAudioInputStream(new File("song.mp3"));
clip.open(ais);
clip.loop(Clip.LOOP_CONTINUOUSLY);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// A GUI element to prevent the Clip's daemon Thread
// from terminating at the end of the main()
JOptionPane.showMessageDialog(null, "Close to exit!");
}
});
} catch (LineUnavailableException | UnsupportedAudioFileException | IOException ex) {
ex.printStackTrace();
}
现在,另一个问题是,默认情况下,Java Audio不会播放MP3文件。您可以通过包含Java Media Framework中的mp3plugin.jar
来添加支持,有关详细信息,请查看Playing MP3 using Java Sound API