在 Java 中播放 .mp3 和 .wav? [英] Playing .mp3 and .wav in Java?
本文介绍了在 Java 中播放 .mp3 和 .wav?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在我的 Java 应用程序中播放 .mp3
和 .wav
文件?我正在使用 Swing.我试着在互联网上寻找类似这样的例子:
How can I play an .mp3
and a .wav
file in my Java application? I am using Swing. I tried looking on the internet, for something like this example:
public void playSound() {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("D:/MusicPlayer/fml.mp3").getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
} catch(Exception ex) {
System.out.println("Error with playing sound.");
ex.printStackTrace();
}
}
但是,这只会播放 .wav
文件.
But, this will only play .wav
files.
同:
http://www.javaworld.com/javaworld/javatips/jw-javatip24.html
我希望能够使用相同的方法播放 .mp3
文件和 .wav
文件.
I want to be able to play both .mp3
files and .wav
files with the same method.
推荐答案
Java FX 有 Media
和 MediaPlayer
类可以播放 mp3 文件.
Java FX has Media
and MediaPlayer
classes which will play mp3 files.
示例代码:
String bip = "bip.mp3";
Media hit = new Media(new File(bip).toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
您将需要以下导入语句:
You will need the following import statements:
import java.io.File;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
这篇关于在 Java 中播放 .mp3 和 .wav?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文