0

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

Freeranger
  • 113
  • 1
  • 10

1 Answers1

1

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
});
Michael Berry
  • 70,193
  • 21
  • 157
  • 216
  • 1
    Note that there's another way to hack this, using [`Platform.startup()`](https://docs.oracle.com/javase/9/docs/api/javafx/application/Platform.html#startup-java.lang.Runnable-), though note that you can't call this method more than once, or if you have called `Application.launch()`, and you cannot call `Application.launch()` after calling it. – James_D May 02 '18 at 13:29
  • @James_D Thanks for that, didn't realise that had crept in since Java 9. – Michael Berry May 02 '18 at 13:32
  • Now I'm going to sound like a jerk, but what is Swing EDT? :) – Freeranger May 02 '18 at 13:33
  • 1
    @Freeranger "EDT" = "Event Dispatch Thread". The thread on which Swing/AWT components are rendered and on which Swing/AWT events are processed. – James_D May 02 '18 at 13:34
  • I did that now, but now, I'm getting music, but it sounds VERY strange, it's the original music with some kind of weird additional sound that takes over completely – Freeranger May 02 '18 at 13:45
  • 1
    I fixed it! The mediaplayer start was in a loop :) – Freeranger May 02 '18 at 19:23