Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JavaFX MediaPlayer correctly?

I'm writing a simple game and trying to play sounds but I can't get it to work when I create the Media object it throws IllegalArgumentException. I'm not much of a Java coder and any help will be appreciated. Here is a sample code:

import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;

public class Main{
    public static void main(String[] args) {

        Media pick = new Media("put.mp3"); //throws here
        MediaPlayer player = new MediaPlayer(pick);
        player.play();
    }
}

Obviously "put.mp3" exists and located in the correct directory, I checked the path using: System.out.println(System.getProperty("user.dir"));

what am I doing wrong here?

like image 780
Dima Maligin Avatar asked Dec 01 '22 16:12

Dima Maligin


1 Answers

The problem is because you are trying to run JavaFX scene graph control outside of JavaFX Application thread.

Run all JavaFX scene graph nodes inside the JavaFX application thread.

You can start a JavaFX thread by extending JavaFX Application class and overriding the start() method.

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {

        Media pick = new Media("put.mp3"); // replace this with your own audio file
        MediaPlayer player = new MediaPlayer(pick);

        // Add a mediaView, to display the media. Its necessary !
        // This mediaView is added to a Pane
        MediaView mediaView = new MediaView(player);

        // Add to scene
        Group root = new Group(mediaView);
        Scene scene = new Scene(root, 500, 200);

        // Show the stage
        primaryStage.setTitle("Media Player");
        primaryStage.setScene(scene);
        primaryStage.show();

        // Play the media once the stage is shown
        player.play();
    }

    public static void main(String[] args) {
         launch(args);
    }
}
like image 145
ItachiUchiha Avatar answered Dec 11 '22 04:12

ItachiUchiha