如何等待JavaFx MediaPlayer完成 [英] How to wait for JavaFx MediaPlayer to finish

查看:61
本文介绍了如何等待JavaFx MediaPlayer完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 MediaPlayer 对象,可以播放视频.视频播放完后,我希望程序隐藏 MediaView 并显示不同的JavaFx实体.但是,当我调用 player.play()时,程序会立即解释后面的代码行,导致 MediaView 根本看不到.

I have a MediaPlayer object which plays a video. When the video is finished playing, I want the program to hide the MediaView and display different JavaFx entities. However, when I call player.play() the program immediately interprets the lines of code which follow, resulting in the MediaView not being visible at all.

public class Level1Controller implements Initializable {

    File file = new File("ngnl.mp4");
    Media media = new Media(file.toURI().toString());
    MediaPlayer player = new MediaPlayer(media);
    @FXML
    MediaView view = new MediaView();


    /**
     * Initializes the controller class.
     */

    @Override
    public void initialize(URL url, ResourceBundle rb) {

        view.setMediaPlayer(player);
        player.play();

        view.setVisible(false); 
    }
}

更多按钮以及类似的按钮将位于JavaFx层次结构中的 MediaView 之下,因此,将其隐藏时,将看到底层的内容.

More buttons and such would be "under" the MediaView in the JavaFx hierarchy, so when it is hidden, the underlying stuff would be seen.

推荐答案

找不到任何提及此问题的官方文档,但我敢肯定,JavaFX会在后台单独播放该媒体文件,因此它不会阻止UI线程.这就是为什么您需要使用

Can't find any official documents that mention this but I'm pretty sure the media file is played on a separate thread under the hood by JavaFX so that it doesn't block the UI thread. This is why you need to use MediaPlayer.setOnEndOfMedia:

view.setMediaPlayer(player);

player.setOnEndOfMedia(() -> {
    view.setVisible(false); 
});    

player.play();

这篇关于如何等待JavaFx MediaPlayer完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆