I'm having a problem with my code. Play button takes 5 clicks to play the movie.
My code is every 15 seconds the media player will automatically pause. But after pausing, the play button takes 5 clicks to make the video playing again.
//auto pause every 15 seconds
int moduloTime = (int) (mediaPlayer.getCurrentTime().toSeconds() % 15);
if(moduloTime == 0){
mediaPlayer.pause();
}else{
mediaPlayer.play();
}
The problem is that you round down the time. This means as long as the number of complete seconds remains divisible by 15, the player is stopped over and over again. You should save the last value you stopped for in some field and prevent your code from stopping again for this second once you press continue.
private static final String URL = ...;
private MediaPlayer mediaPlayer;
public void start(Stage primaryStage) {
Media media = new Media(URL);
mediaPlayer = new MediaPlayer(media);
mediaPlayer.currentTimeProperty().addListener(new ChangeListener<Duration>() {
private int lastStop = 0;
@Override
public void changed(ObservableValue<? extends Duration> observable, Duration oldValue, Duration newValue) {
int value = (int) newValue.toSeconds();
if (lastStop != value && value % 15 == 0) {
lastStop = value; // prevent this "stop" from triggering the pause again
mediaPlayer.pause();
}
}
});
Button btn = new Button("play");
btn.setOnAction(evt -> mediaPlayer.play());
Scene scene = new Scene(new StackPane(btn), 300, 300);
primaryStage.setScene(scene);
primaryStage.show();
}