如何正确使用JavaFX MediaPlayer?

我正在编写一个简单的游戏并试图播放声音,但是当我创建Media对象时它无法使它工作,它会抛出IllegalArgumentException 。 我不是一个Java编码器,任何帮助将不胜感激。 这是一个示例代码:

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

显然“put.mp3”存在并位于正确的目录中,我使用了以下方法检查路径: System.out.println(System.getProperty("user.dir"));

我在这做错了什么?

问题是因为您尝试在JavaFX Application thread之外运行JavaFX场景图控件。

运行JavaFX应用程序线程内的所有JavaFX场景图节点。

您可以通过扩展JavaFX Application类并覆盖start()方法来启动JavaFX线程。

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

好的,多亏了@ItachiUchiha对此问题的见解,我能够解决我的问题,似乎任何使用javaFX的代码都必须在javaFX应用程序内部运行Thread但不是每个程序都必须使用javaFX API。 简而言之,我所做的就是从Application.start(Stage ps)开始我的游戏,如下所示:

 import javafx.application.Application; import javafx.stage.Stage; public class Main extends Application { @Override public void start(Stage primaryStage) { new Game(9,9,BasicRobot.FACING.SOUTH, 19); } public static void main(String[] args) throws InterruptedException { launch(); } } 

这样Game类及其创建和使用的所有内容都可以使用javaFX。 为了播放声音,我创建了一个Utils类:

 import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; public class Utils { public static void playSound(String fileName){ Media m = new Media("file:///" + System.getProperty("user.dir").replace('\\', '/') + "/" + fileName); MediaPlayer player = new MediaPlayer(m); player.play(); } } 

现在我要做的就是播放声音,从我游戏中的任何地方调用Utils.playSound("fileName.mp3")