Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

java - How to use JavaFX MediaPlayer correctly?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...