To play an mp3 file, I use the javafx.scene.media.MediaPlayer class. But I noticed that currentTimeProperty is not reliable after using the seek() method.
The initMediaPlayer() method in the code below is called when the user selects an mp3 file. Playback time is displayed in the time slider ( =timeSlider ), which the user can move to start playback from anywhere in the song. The current position in the song is also displayed on the label ( =timeLabel ).
When I start playback using play() , and when I pause or restart the song using pause() or stop() , everything works fine.
The problem is that after using seek() currentTimeProperty no more true. This becomes very noticeable at the end of the song, then currentTimeProperty sometimes comes up to 4 seconds longer than the total song time.
What is the cause of this problem and is there a way around it?
private void initMediaPlayer() { try { audio = new Media(audioFile.toURI().toURL().toString()); audioPlayer = new MediaPlayer(audio); } catch (MalformedURLException ex) { Logger.getLogger(MainWindowController.class.getName()) .log(Level.SEVERE, null, ex); } audioPlayer.currentTimeProperty().addListener(new InvalidationListener() { public void invalidated(Observable ov) { Duration time = audioPlayer.getCurrentTime(); Duration total = audioPlayer.getTotalDuration(); if (!timeSlider.isValueChanging() && total.greaterThan(Duration.ZERO)){ timeSlider.setValue(time.toMillis() / total.toMillis() * 100); } timeLabel.setText(formatTime(time,total)); } }); timeSlider.valueChangingProperty().addListener(new InvalidationListener() { public void invalidated(Observable ov) { audioPlayer.seek(audioPlayer.getTotalDuration() .multiply(timeSlider.getValue() / 100.0)); } }); }
source share