媒体播放器在Java中无法正常工作



我有一个关于Java的问题,与用于播放介绍性视频的类MediaPlayer有关。关键是,在运行我的应用程序时,视频有时播放正确,有时播放不正确,大多数时候播放不正确。通过说它没有正确播放,我指的是音频被播放但图像没有。所以我可以得出结论,MediaPlayer工作不正常。

这是我的应用程序的代码:

/**
* Main class of the application.
*/
public class Main{
// Define the variable for the window of the game.
public static JFrame window;
// Define the variable for the introductory video.
public static MediaPlayer video;
/**
* Main function of the application.
*/
public static void main(String[] args){
// Prevent the JavaFX toolkit from closing.
Platform.setImplicitExit(false);
// Create the window of the game.
window = new JFrame();
// Set the title.
window.setTitle("Chip");
// Set the resolution as 1920 x 1280.
window.setSize(1926,1343);
// Set the location as in the middle of the screen.
window.setLocationRelativeTo(null);
// Set the operation when the window closes.
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Disable the maximization and resizable mode.
window.setResizable(false);
// Show the window.
window.setVisible(true);
// Show the introductory video.
showVideo();
// Pause the execution of the application for 30 seconds (duration of the introductory video).
try{
Thread.sleep(30000);
}catch (InterruptedException interruptedException){
interruptedException.printStackTrace();
}
}

/**
* Shows the introductory video.
*/
public static void showVideo(){
// Create the video panel and the JavaFX panel.
JPanel panelVideo = new JPanel();
JFXPanel panelJavaFX = new JFXPanel();
// Set the size of the video panel as the resolution of the introductory video (1920 x 1080).
panelVideo.setSize(1920,1080);
// Set the location of the video panel as in the middle of the window of the game.
int coordinateX = (window.getWidth() - panelVideo.getWidth() - window.getInsets().left - window.getInsets().right) / 2;
int coordinateY = (window.getHeight() - panelVideo.getHeight() - window.getInsets().top - window.getInsets().bottom) / 2;
panelVideo.setLocation(coordinateX,coordinateY);
// Define the video file.
String filename = "./media/video/introduction.mp4";
video = new MediaPlayer(new Media(new File(filename).toURI().toString()));
// Add the video to the JavaFX panel.
panelJavaFX.setScene(new Scene(new Group(new MediaView(video))));
// Add the JavaFX panel to the video panel.
panelVideo.add(panelJavaFX);
// Add the video panel to the window of the game.
window.getContentPane().setLayout(null);
window.add(panelVideo);
// Play the video.
video.play();
}
}

在初始化 MediaPlayer 后直接设置您的video.play();方法,至少对我来说似乎可以修复它,即:

video = new MediaPlayer(new Media(new File(filename).toURI().toString()));
video.play();

这个问题的正确答案是:

我将变量panelJavaFX(JFXPanel(直接添加到变量window(JFrame(,所以我最终没有使用中间变量panelVideo(JPanel(。

最新更新