从 JavaFX 中的媒体文件中检索元数据

Retrieving metadata from media files in JavaFX

我有一个 MediaPlayer,可以播放用户从音乐库中选择的音乐。创建库时,歌曲需要按标题列出。我知道我可以使用媒体 object 获取所有元数据。但这带来了两个问题。 I) 整个过程对于大型媒体来说非常耗时耗资源 collection II) 即使我使用以下代码

for(String path : paths){
      Media m = new Media(path);
      String title = (String)m.getMetadata().get("title");
      String album = (String)m.get metadata().get("album");
      String artist = (String)m.get metadata().get("artist");
}

尽管文件本身有元数据,但大多数时候艺术家、标题、专辑字符串都具有空值。分析媒体 class 我了解到在获取元数据时其中存在某种线程,这就是快速请求返回 null 的原因。但我不能每次都等待(milis),因为那会非常耗时。任何解决方法??

来自 Media 文档:

The media information is obtained asynchronously and so not necessarily available immediately after instantiation of the class. All information should however be available if the instance has been associated with a MediaPlayer and that player has transitioned to MediaPlayer.Status.READY status. To be notified when metadata or Tracks are added, observers may be registered with the collections returned by getMetadata() and getTracks(), respectively.

因此,您可能需要添加侦听器并 运行 在侦听器中进行处理。监听器可以直接添加到元数据上,也可以添加到关联播放器的状态上。例如:

Media media = new Media(myMediaLocationString);
media.getMetadata().addListener((MapChangeListener<String, Object>) change -> {
    // code to process metadata attribute change.
});
MediaPlayer player = new MediaPlayer(media);

我还没有尝试使用示例程序对此进行测试,但是根据我对文档的理解,它应该可以工作;-)

memory usage. Creating 2000 Media objects is really freezing the display. What to do?

冻结和内存消耗是不同的事情,可以不相关。

要防止 UI 线程阻塞,请在创建媒体对象时不要阻塞 UI 线程,请使用 concurrency facilities. There are many example for different scenarios in the Task 文档。编写并发代码时要小心,不要修改活动场景图中的任何内容(例如,显示给用户)。

为了减少内存消耗,不要保留对不再需要的媒体的引用,并及时适当地 dispose 媒体播放器资源。

还要考虑您是否真的需要创建 2000 个媒体对象,或者是否更愿意最初只创建该数量的一个子集,然后(也许)根据需要动态创建其他对象。