简体   繁体   中英

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

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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM