如何正确使用 JavaFX MediaPlayer? [英] How to use JavaFX MediaPlayer correctly?
问题描述
我正在编写一个简单的游戏并尝试播放声音,但是当我创建它抛出 IllegalArgumentException
的 Media 对象时,我无法让它工作.我不是一个 Java 编码员,任何帮助将不胜感激.这是一个示例代码:
import javafx.scene.media.Media;导入 javafx.scene.media.MediaPlayer;公共课主要{公共静态无效主(字符串 [] args){媒体选择 = new Media("put.mp3");//这里抛出MediaPlayer player = new MediaPlayer(pick);播放器播放();}}
显然put.mp3"存在并且位于正确的目录中,我使用以下方法检查了路径:System.out.println(System.getProperty("user.dir"));
>
我在这里做错了什么?
问题是因为您试图在 JavaFX 应用程序线程
之外运行 JavaFX 场景图控件.
在 JavaFX 应用程序线程内运行所有 JavaFX 场景图节点.
您可以通过扩展 JavaFX Application
类并覆盖 start()
方法来启动 JavaFX 线程.
public class Main extends Application {@覆盖公共无效开始(阶段primaryStage){媒体选择 = new Media("put.mp3");//用你自己的音频文件替换它MediaPlayer player = new MediaPlayer(pick);//添加一个mediaView,用于显示媒体.这是有必要的 !//这个mediaView被添加到一个PaneMediaView mediaView = new MediaView(player);//添加到场景Group root = new Group(mediaView);场景场景 = 新场景(root, 500, 200);//显示舞台primaryStage.setTitle("媒体播放器");primaryStage.setScene(场景);primaryStage.show();//舞台显示后播放媒体播放器播放();}公共静态无效主(字符串 [] args){发射(参数);}}
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?
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 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屋!