JavaFx audio file not playing

2.5k views Asked by At

I have the following code. No sound is being played I have no idea what I am doing wrong. I have a file called "Test" in the directory specified. It is of .mp3 format.

@Override
public void start(Stage stage) throws Exception
{
    Media sound = new Media("file:///C:/Users/name/Music/HQ/Test.mp3");
    MediaPlayer mediaPlayer = new MediaPlayer(sound);
    mediaPlayer.setAutoPlay(true);

    VBox root = new VBox();
    root.getChildren().addAll();

    Scene scene = new Scene(root, 500, 500);
    stage.setScene(scene);
    stage.show();

}

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

There are 3 answers

0
Calculator On

You have to call mediaPlayer.play(); somewhere. setAutoPlay() only sets the autoPlay-property.

7
GOXR3PLUS On

1)If it is inside your project the .mp3 file in [resources/music/test.mp3]:

Media media = null;
try {
  media = new Media(getClass().getResource("/music/Test.mp3").toURI().toString());
} catch (URISyntaxException e) {
  e.printStackTrace();
} 

2)If it is outside the project for example on file:///C:/Users/name/Music/HQ/Test.mp3

 Media media = null;
 try {
   media = new Media("file:C:/Users/name/Music/HQ/Test.mp3");
 } catch (URISyntaxException e) {
   e.printStackTrace();
 } 

Have a look on this question also : Getting a mp3 file to play using javafx

And here how it downloads the Image it will help you.

0
Kamil Latosinski On

I had the same problem. I wanted to play 4 min mp3 track on menu screen in my game. I've converted from mp3 to wav. Still nothing. Then I've tried shorter sound (1 sec gong sound)... and it worked! However the sound was like cut in the middle. Well, that made me suspicious, so I've decided to run this inside a Thread and it worked! Then I've switched back to primary sound and now it was playing just fine.

For now I don't understand two things:

  • why running this inside Thread helps
  • why .wav works and .mp3 doesn't

It's not much for now but maybe it will help someone :) I will update my answer as soon as I find out!