Playing mp3 audio with JavaFx

Java had audio support since ages but there was no direct way play mp3 files in java.

Thanks to JavaFx , you can now directly play mp3 files from your program. In this way you can avoid storing .wave audio files which are huge in size.

In your JavaFx project you need to put the following lines of code

import java.io.File;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
String source = new File(“audio.mp3″).toURI().toString();
Media media = null;
media = new Media(source);
MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();

Note that this will play audio file from the current working directory. Usually the same directory where the above code file exists or the final executable jar directory. You can confirm the directory using the following code.

System.out.println(new File(“.”).getCanonicalPath());

There are many other ways to add mp3 capability to Java but I felt using JavaFx is the easiest way specially because of the fact that since the JDK 7 update 6 contains JavaFx 2.2 .