D
D
devpy142021-08-15 18:52:22
Java
devpy14, 2021-08-15 18:52:22

Why does the getDuration() method on the Media object return UNKNOWN?

I am writing an mp3 player. There is a "beginTimer()" method that counts the time while the song is playing and moves the slider according to it:

private void beginTimer() {
        timer = new Timer();

        double max = media.getDuration().toSeconds();
        songDuration.setMax(max);

        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                double current = mediaPlayer.getCurrentTime().toSeconds();
                double end = media.getDuration().toSeconds();

                running = true;
                songDuration.setValue((int) current);

                if (current / end == 1) {
                    cancelTimer();
                    Platform.runLater(() -> nextMedia());
                }
            }
        };
        timer.scheduleAtFixedRate(timerTask, 0, 1000);
    }


When playing the first song, everything works correctly, the "max" variable returns the duration of the song in seconds. But when the method is called again, the getDuration() method returns NaN, and so on with each subsequent song. Moreover, if you transfer the lines
double max = media.getDuration().toSeconds();
songDuration.setMax(max);

in the run method, NaN is also returned first, but then a normal numeric value is returned.

Tried to do it like this:
mediaPlayer.setOnReady(() -> {
     double max = media.getDuration().toSeconds();
     songDuration.setMax(max);
});

The result is that when playing a song for the first time, this line simply does not work, but on subsequent song changes it works fine

. Why is this happening?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question