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?
Ok thanks to @ItachiUchiha insight on the matter I was able to solve my problem, It seems that any code that uses javaFX must run from within javaFX application Thread but not every program has to use javaFX API. In short what I did is start my game from within the
Application.start(Stage ps)
like so:That way the Game class and everything it creates and uses can use javaFX. To play the sounds I created a Utils class:
and now all I have to do to play a sound is call
Utils.playSound("fileName.mp3")
from anywhere inside my Game.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 thestart()
method.