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();
}
}
But, this will only play .wav
files.
The same with:
http://www.javaworld.com/javaworld/javatips/jw-javatip24.html
I want to be able to play both .mp3
files and .wav
files with the same method.
To add MP3 reading support to Java Sound, add the
mp3plugin.jar
of the JMF to the run-time class path of the application.Note that the
Clip
class has memory limitations that make it unsuitable for more than a few seconds of high quality sound.The easiest way I found was to download the JLayer jar file from http://www.javazoom.net/javalayer/sources.html and to add it to the Jar library http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29
Here is the code for the class
and here are the imports
It's been a while since I used it, but JavaLayer is great for MP3 playback
Do a search of freshmeat.net for JAVE (stands for Java Audio Video Encoder) Library (link here). It's a library for these kinds of things. I don't know if Java has a native mp3 function.
You will probably need to wrap the mp3 function and the wav function together, using inheritance and a simple wrapper function, if you want one method to run both types of files.
You need to install JMF first (download using this link)
don't forget to add JMF jar files
Use this library: import sun.audio.*;