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.
you can play .wav only with java API:
code:
And play .mp3 with jLayer
I would recommend using the BasicPlayerAPI. It's open source, very simple and it doesn't require JavaFX. http://www.javazoom.net/jlgui/api.html
After downloading and extracting the zip-file one should add the following jar-files to the build path of the project:
Here is a minimalistic usage example:
Required imports:
That's all you need to start playing music. The Player is starting and managing his own playback thread and provides play, pause, resume, stop and seek functionality.
For a more advanced usage you may take a look at the jlGui Music Player. It's an open source WinAmp clone: http://www.javazoom.net/jlgui/jlgui.html
The first class to look at would be PlayerUI (inside the package javazoom.jlgui.player.amp). It demonstrates the advanced features of the BasicPlayer pretty well.
Java FX has
Media
andMediaPlayer
classes which will play mp3 files.Example code:
You will need the following import statements:
I wrote a pure java mp3 player: mp3transform.
To give the readers another alternative, I am suggesting JACo MP3 Player library, a cross platform java mp3 player.
Features:
For a complete list of its methods and attributes you can check its documentation here.
Sample code:
For more details, I created a simple tutorial here that includes a downloadable sourcecode.
Using standard javax.sound API, a single Maven dependency, completely Open Source (Java 7 required) :
pom.xml
Code
References: