我在 JavaFX 上编写程序,它必须显示窗口,在上面播放视频,播放后隐藏窗口,然后在随机时间后再次重复此操作。我需要知道如何在媒体播放器完成播放当前视频时进行随机延迟。我的想法是这些 - 如果在
scene.hide()
之后添加 player.play()
,窗口在播放完成之前被隐藏,跟随播放器在另一个线程中工作。但是如果我在命令 TimeUnit.SECONDS.sleep(10)
之后通过 player.play()
添加延迟,视频播放将在 10 秒后开始。请解释,实际上发生了什么,以及播放完成后如何添加延迟。
我的代码:
import java.io.File;
import java.lang.management.ManagementFactory;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.input.KeyCombination;
import java.util.concurrent.TimeUnit;
public class Main extends Application implements Runnable {
private String Dir = System.getProperty("./");
private Stage stage;
private boolean fl;
public static void main(String[] args) throws Exception{
launch(args);
}
public void run() { //if playing is complete - hide window
//System.out.printf("Media player thread is %d \n",Thread.currentThread().getId());
this.stage.hide();
}
private static int randomIntBetween(int first, int last) {
int rnd_int= (int)(first + Math.round(Math.random()*Math.abs((last-first))));
return rnd_int;
}
@Override
public void start(Stage stage) throws Exception {
this.stage=stage;
String[] video_paths = {"lp.mp4","sc_1.mp4"};
stage.setFullScreen(true);
stage.setFullScreenExitHint("");
stage.setFullScreenExitKeyCombination(javafx.scene.input.KeyCombination.NO_MATCH);
while (true){
String video_path = video_paths[randomIntBetween(0,video_paths.length-1)];//Get random video (path)
File f = new File(video_path);
Media media = new Media(f.toURI().toURL().toString());
javafx.scene.media.MediaPlayer player = new javafx.scene.media.MediaPlayer(media);
MediaView viewer = new MediaView(player);
//change width and height to fit video
DoubleProperty width = viewer.fitWidthProperty();
DoubleProperty height = viewer.fitHeightProperty();
width.bind(Bindings.selectDouble(viewer.sceneProperty(), "width"));
height.bind(Bindings.selectDouble(viewer.sceneProperty(), "height"));
viewer.setPreserveRatio(true);
StackPane root = new StackPane();
root.getChildren().add(viewer);
//set the Scene
Scene scenes = new Scene(root);
stage.setScene(scenes);
player.setOnEndOfMedia(this);
//System.out.printf("Main thread is %d \n",Thread.currentThread().getId());
stage.show();
player.play();
//this.stage.hide();
//TimeUnit.SECONDS.sleep(randomIntBetween(3,100);
break;//added for single iteration
}
}
}
如果我在 player.play() 之后添加 break,我的代码可以工作。但这不是我的问题的解决方案。