Search code examples
javafxmp3media-player

JavaFX MediaPlayer switches to state PLAYING, but doesn't play mp3


I'm trying to play an mp3 file using the JavaFX MediaPlayer. It loads the file and switches to the PLAYING state without any errors, but it doesn't play the file and the currentTimeProperty doesn't change either. What am I doing wrong?

public class Test extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        MediaPlayer player = new MediaPlayer(new Media(
                new File("sounds/sound.mp3").toURI().toString()
        ));

        Button btn = new Button("Play");
        btn.setOnAction(event -> player.play());
        VBox pane = new VBox(10, btn);
        pane.setAlignment(Pos.CENTER);
        Scene scene = new Scene(pane, 100, 100);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

Solution

  • The code you have provide works fine as it is for me.I am not an expert with MediaPlayer and MediaView classes but assuming you are loading the media correctly and not getting a MediaException: MEDIA_UNAVAILABLE while you load the mp3 file, there are two possible causes for your problem.

    • Your file format is not supported. Looking at the Java Doc about the supported formats you will see that the supported mp3 formats are: Raw MPEG-1, 2, and 2.5 audio; layers I, II, and III; all supported combinations of sampling frequencies and bit rates. So if your file is not supported you will not be able to play it. Now you can check if there is any kind of error using the code below.

    player.setOnError(() -> System.out.println("Error : " + player.getError().toString()));

    • I had a similar problem in the past with a fresh windows operating system. If you are using Windows, your operating system may not have the necessary codecs in order to play the video/audio. In that, your JavaFX application will try to play the audio but you are not going to hear any sound. To fix that you could try to install some audio codecs which I am not familiar with this matter but I would suggest the K-Lite Codec Pack ( make a google search and you will be fine )