«

»

Jul 15

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 .

2 pings

  1. Praveen Kumar

    Very Useful :) Thank You.

  1. Run JavaFx without any prerequisite runtime installation » Neil Ghosh

    [...] « Playing mp3 audio with JavaFx [...]

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Plugin from the creators of Brindes Personalizados :: More at Plulz Wordpress Plugins