如何正确使用JavaFX MediaPlayer? [英] How to use JavaFX MediaPlayer correctly?
问题描述
我正在编写一个简单的游戏并尝试播放声音,但是当我创建它抛出的Media对象时,我无法使其工作 IllegalArgumentException
。我不是一个Java编码器,任何帮助将不胜感激。
以下是示例代码:
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();
}
}
显然put.mp3存在且位于正确的目录,我检查路径使用: System.out.println(System.getProperty(user.dir));
Obviously "put.mp3" exists and located in the correct directory, I checked the path using: System.out.println(System.getProperty("user.dir"));
我在这里做错了什么?
推荐答案
问题是因为你试图运行JavaFX场景图控件在之外的JavaFX应用程序线程
。
The problem is because you are trying to run JavaFX scene graph control outside of JavaFX Application thread
.
在JavaFX应用程序线程中运行所有JavaFX场景图节点。 / em>
Run all JavaFX scene graph nodes inside the JavaFX application thread.
您可以通过扩展JavaFX Application
类并覆盖 start()
method。
You can start a JavaFX thread by extending JavaFX Application
class and overriding the start()
method.
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);
}
}
这篇关于如何正确使用JavaFX MediaPlayer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!