JavaFX can't play mp3 files

2.6k views Asked by At

I followed this tutorial: http://what-when-how.com/javafx-2/playing-audio-using-the-media-classes-javafx-2-part-1/

package audioVideo;

import java.net.URL;

import javafx.application.Application;
import javafx.scene.media.*;
import javafx.stage.*;

public class AudioPlayer1 extends Application
{
    public static void main(String args[])
    {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage)
    {
        URL resource = getClass().getResource("resources/sample.mp3");
        Media media = new Media(resource.toString());
        MediaPlayer mediaPlayer = new MediaPlayer(media);
        mediaPlayer.play();

        primaryStage.setTitle("Audio Player 1");
        primaryStage.setWidth(200);
        primaryStage.setHeight(200);
        primaryStage.show();
    }
}

And I have the appropriate resources folder in the same directory as the respective .class file, but I still can't play the audio. The mp3 file isn't the same one in the tutorial, but I also have a .wav equivalent and found that JavaFX can play *.wav files out of the box but not mp3 files. What's going on?

I'm using Ubuntu 15.04 64-bit via Eclipse. It can't be a resource issue because the .wav file is in the same folder as the .mp3 one, but the former can be played yet the latter can't. Do I need certain dependencies in order for the mp3 file to be played correctly? I can play the mp3 files from Ubuntu directly.

1

There are 1 answers

0
Rahul S. On

First, import the following:

import java.nio.file.Paths;

Then, when you create your media, do the following:

Media media = new Media(("yourAudio.fileExtension").toUri().toString());
MediaPlayer player = new MediaPlayer(media);

That should do the trick (for a mp3 at least).