javafx视频播放器timeSlider

时间:2016-06-11 15:36:00

标签: javafx slider

如何在视频播放时让滑块移动?

初始化:

BorderPane border = new BorderPane();
HBox bar = new HBox(10);
//Button play = new Button("Play");
//Button pause = new Button("Pause");

媒体:

    Media media = new Media(Paths.get("C://video.mp4").toUri().toString());
    MediaPlayer player = new MediaPlayer(media);
    MediaView mediaView = new MediaView(player);

定位:

    bar.getChildren().addAll(play,pause,timeSlider);
    bar.setAlignment(Pos.CENTER);
    border.setCenter(mediaView);
    border.setBottom(bar);

有关如何让我的滑块在视频播放时移动的任何建议吗?

编辑:

找到答案:

player.currentTimeProperty().addListener((obs, oldTime, newTime) -> {
        if (!timeSlider.isValueChanging()) {
            timeSlider.setValue(newTime.toSeconds());
        }
    });

1 个答案:

答案 0 :(得分:1)

我现在正在处理类似的问题。这应该适合你:

// Listen to the slider. When it changes, seek with the player.
// MediaPlayer.seek does nothing when the player is stopped, so the play/pause button's handler
// always sets the start time to the slider's current value, and then resets it to 0 after starting the player.
InvalidationListener sliderChangeListener = o-> {
    Duration seekTo = Duration.seconds(timeSlider.getValue());
    player.seek(seekTo);
});
timeSlider.valueProperty().addListener(sliderChangeListener);

// Link the player's time to the slider
player.currentTimeProperty().addListener(l-> {
    // Temporarily remove the listener on the slider, so it doesn't respond to the change in playback time
    // I thought timeSlider.isValueChanging() would be useful for this, but it seems to get stuck at true
    // if the user slides the slider instead of just clicking a position on it.
    timeSlider.valueProperty().removeListener(sliderChangeListener);

    // Keep timeText's text up to date with the slider position.
    Duration currentTime = player.getCurrentTime();
    int value = (int) currentTime.toSeconds();
    timeSlider.setValue(value);    

    // Re-add the slider listener
    timeSlider.valueProperty().addListener(sliderChangeListener);
});