我试图找出如何从媒体获取元数据已有一段时间,但到目前为止没有任何效果。我有Song类,其中有诸如标题,艺术家等SimpleStringProperties。我尝试在类构造函数中为其设置值:
private final SimpleStringProperty title;
private final SimpleStringProperty artist;
public Song(String path) {
this.song = new MediaPlayer(new Media(path));
this.artist = new SimpleStringProperty(this, "artist");
this.title = new SimpleStringProperty(this, "title");
this.song.setOnReady(() -> {
title.set(song.getMedia().getMetadata().get("title").toString());
artist.set(song.getMedia().getMetadata().get("artist").toString());
});
}
然后,我尝试在fxml控制器中制作一首新歌:
Song song = new Song(path);
System.out.println(song.getTitle());
System.out.println(song.getArtist());
我在控制台中看到
null
null
我知道在
setOnReady()
方法中它可以正确显示标题和艺术家。我已经使用Platform.runLater()
解决方案,但是当有更多新歌曲时,它无法正常工作。我已经读过有关synchronized()
的内容,但我不知道如何使用它。我正在等待一些解决方案。提前致谢 :) 最佳答案
您在调用处理程序之前(即在getTitle()
准备就绪之前)正在调用getArtist()
和MediaPlayer
。
大概您真的不想将它们显示在系统控制台上,而只是为了进行测试。尝试类似
Label titleLabel = new Label();
Label artistLabel = new Label();
Song song = new Song(path);
titleLabel.textProperty().bind(song.titleProperty());
artistLabel.textProperty().bind(song.artistProperty());
然后在用户界面中显示这些标签。当数据可用时,它们将自动更新。