我的JavaFX媒体播放器不一致地显示视频。有时第一次尝试就成功了,有时需要3到4次尝试。按钮和其他事件确实发生了,只是视频没有被显示/链接到MediaView。文件是通过fileChooser被选中的我认为与此相关的东西才是真正的问题。我将把控制器的相关代码放在下面:
@FXML
private void handleOpenFile() {
// Create a file chooser dialog and set the initial directory
FileChooser fileChooser = new FileChooser();
fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
// Filter for media files
FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter(
"Media Files (*.mp4, *.mp3, *.wav, *.jpg, *.png)", "*.mp4", "*.mp3", "*.wav", "*.jpg", "*.png");
fileChooser.getExtensionFilters().add(filter);
// Show the file chooser dialog and get the selected file
Stage stage = (Stage) mediaView.getScene().getWindow();
openFile(fileChooser.showOpenDialog(stage));
}
private void openFile(File file){
if (file != null) {
this.file=file;
// Check if the selected file is a media file or an image
String filename = file.getName();
String extension = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
if (extension.equals("jpg") || extension.equals("png")) {
// Display the selected image in the image view
disableVideo();
imageView.setImage(new Image(file.toURI().toString()));
} else {
// Create a media player and set it to the media view
disableImage();
Media media = new Media(file.toURI().toString());
mediaPlayer = new MediaPlayer(media);
mediaView.setMediaPlayer(mediaPlayer);
// Bind the time slider to the media player's current time
timeSlider.valueProperty().addListener((observable, oldValue, newValue) -> {
if (timeSlider.isValueChanging()) {mediaPlayer.seek(Duration.seconds(newValue.doubleValue()));}
});
mediaPlayer.currentTimeProperty().addListener((observable, oldValue, newValue) -> {
if (!timeSlider.isValueChanging()) {timeSlider.setValue(newValue.toSeconds());}
});
mediaPlayer.setOnReady(() -> timeSlider.setMax(mediaPlayer.getMedia().getDuration().toSeconds()));
}
}
}
private void disableImage(){
mediaView.setVisible(true);
imageView.setVisible(false);
playButton.setVisible(true);playButton.setDisable(false);
timeSlider.setVisible(true);timeSlider.setDisable(false);
}
private void disableVideo(){
pause();
mediaView.setVisible(false);
imageView.setVisible(true);
playButton.setVisible(false);playButton.setDisable(true);
timeSlider.setVisible(false);timeSlider.setDisable(true);
}
private void pause(){
if (mediaPlayer != null) {
mediaPlayer.pause();
isPlaying = false;
playButton.setText("Play");
}
}
@FXML
private void handlePlay() {
if (mediaPlayer != null && !isPlaying) {
mediaPlayer.play();
isPlaying = true;
playButton.setText("Pause");
mediaPlayer.setOnEndOfMedia(() -> {
mediaPlayer.seek(Duration.ZERO);
pause();
});
}else pause();
}
@FXML
private void handleTimeSliderChanged() {
if (mediaPlayer != null) {
mediaPlayer.seek(mediaPlayer.getMedia().getDuration()
.multiply(timeSlider.getValue() / timeSlider.getMax()));
}
}
请尝试以下解决方案:
- 用JavaFX编码检查视频的编码;
- 检查视频分辨率,它可能对媒体视图来说太高了
- 也可以查看媒体视图布局属性,仔细检查其大小。
如果问题仍然存在,尝试将JavaFX库更改为另一个。(也可以考虑显示整个源代码以供进一步讨论)