How can I play a .mp3 and a .wav in my java application? I am using Swing, I tried looking on the internet, for 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();
}
}
But, this will only play .wav files.
The same with:
I want to be able to play both .mp3 files and .wav files with the same method.
解决方案
Java FX has Media and MediaPlayer classes which will play mp3 files.
Example code:
String bip = "bip.mp3";
Media hit = new Media(bip);
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
You will need the following import statements:
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;