Skip to content
Advertisement

MediaPlayer.getTotalDuration().toSeconds() returns NaN when called in Initialize method

I am working on MediaPlayer using JavaFX to finish javaFX course. I am trying to set file total duration to the slider max property. Then I want to add Listener to the currentTimeProperty so the slider is tracking the timeline.

I wrote a code that works perfectly fine:

timeSlider.setMax(mediaPlayerMain.getTotalDuration().toSeconds());
System.out.println("Max value: " + mediaPlayerMain.getTotalDuration().toSeconds());
mediaPlayerMain.currentTimeProperty().addListener(new ChangeListener() {

    @Override
    public void changed(ObservableValue o, Object oldVal, Object newVal) {
        timeSlider.setValue(mediaPlayerMain.getCurrentTime().toSeconds());
    }
    
});

It works when I call it once the video is already playing. The problem is that I want to call it once the MediaView is ready so the slider works automatically from the beginning. If I put it in the initialize method the mediaPlayerMain.getTotalDuration().toSeconds() returns NaN so the period has to be UNKNOWN according to the Duration API.

How to wait for the mediaPlayer object to be ready so the slider is working? Any help appreciated, thanks in advance!

Advertisement

Answer

Doesn’t something like

@FXML
private Slider timeSlider ;

@FXML
private MediaPlayer mediaPlayerMain ;

@FXML
private void initialize() {
    if (mediaPlayerMain.getStatus() == MediaPlayer.Status.UNKNOWN) {
        mediaPlayerMain.statusProperty().addListener((obs, oldStatus, newStatus) -> {
            if (newStatus == MediaPlayer.Status.READY) {
                initializeSlider();
            } 
        });
    } else {
        initializeSlider();
    }
}

private void initializeSlider() {
    timeSlider.setMax(mediaPlayerMain.getTotalDuration().toSeconds());
    mediaPlayerMain.currentTimeProperty().addListener((obs, oldTime, newTime) -> 
        timeSlider.setValue(newTime.toSeconds()));
}

work?

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement