我试图使用JavaFX MediaPlayer播放mp3文件。它加载文件并切换到PLAYING状态而没有任何错误,但它没有播放文件,currentTimeProperty也没有改变。我做错了什么?
public class Test extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
MediaPlayer player = new MediaPlayer(new Media(
new File("sounds/sound.mp3").toURI().toString()
));
Button btn = new Button("Play");
btn.setOnAction(event -> player.play());
VBox pane = new VBox(10, btn);
pane.setAlignment(Pos.CENTER);
Scene scene = new Scene(pane, 100, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
}
答案 0 :(得分:1)
您提供的代码可以正常使用。我不是MediaPlayer和MediaView类的专家,但假设您正在正确加载媒体而没有在加载mp3文件时获得MediaException: MEDIA_UNAVAILABLE
,你的问题可能有两个原因。
player.setOnError(() -> System.out.println("Error : " + player.getError().toString()));
答案 1 :(得分:0)
我想你忘记了一部分试试这个
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
MediaPlayer player = new MediaPlayer(new Media(
new File("sounds/sound.mp3").toURI().toString()
));
Button btn = new Button("Play");
btn.setOnAction(event -> player.play());
VBox pane = new VBox(10, btn);
pane.setAlignment(Pos.CENTER);
Scene scene = new Scene(pane, 100, 100);
MediaView mediaView = new MediaView(player);
((Group)scene.getRoot()).getChildren().add(mediaView);
primaryStage.setScene(scene);
primaryStage.show();
}