Freeranger
Freeranger

Reputation: 111

Javafx music player not working

I'm coding a game in java, and I decided to add music to it. I tried with this code:

URL resource = getClass().getResource("music.mp3");
     MediaPlayer a = new MediaPlayer(new Media(resource.toString()));
     a.setOnEndOfMedia(new Runnable() {
           public void run() {
             a.seek(Duration.ZERO);
           }
       });
      a.play();

But for some reason, I get this error:

https://pastebin.com/UPkTbWHh

The file music.mp3 is in the same folder as the class I'm running it from, and the code is running in the tick() method. Do anybody have an idea about how I can fix this?

Thanks, Lukas

Upvotes: 0

Views: 274

Answers (1)

Michael Berry
Michael Berry

Reputation: 72254

You're attempting to execute the above code from outside the context of a JavaFX app. MediaPlayer is a JavaFX component, so relies on the Toolkit being initialised, you can't (by default) just spin up a JFX component as you please.

The "proper" way is to subclass a JFX Application and then launch your application from there, which will initialise the JFX platform properly.

The "hack" way is to run the following line of code in the Swing EDT:

new JFXPanel();

...which will also have the side effect of initialising the JFX toolkit and allow you to create other JFX components.

As pointed out in the comments, since Java 9 you can use the less hacky method of:

Platform.startup(() -> {
    //Code to run on JFX thread
});

Upvotes: 1

Related Questions