I am a newbie to both Java and JavaFX, I\'ve spent the last couple years developing on Python with QT, and I am now developing in Java and JavaFX.
I am developing a
If you read the javadoc for Media
class, it says you should wait for the media player to be ready:
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 Status.READY status
So you just need to create an instance of MediaPlayer
and listen for the Status.READY
:
File filestring = new File("my/file/dir/file.mp3");
Media file = new Media(filestring.toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(file);
mediaPlayer.setOnReady(new Runnable() {
@Override
public void run() {
System.out.println("Duration: "+file.getDuration().toSeconds());
// display media's metadata
for (Map.Entry<String, Object> entry : file.getMetadata().entrySet()){
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// play if you want
mediaPlayer.play();
}
});
It looks like the Media needs some time to get fully initialized. Add a Thread sleep beforebthe getDuration line and try again!