这就是我在控制器中所拥有的:
@FXML
private MediaView mediaView;
在处理按钮按下的方法中,我得到了filechooser:
File file = fileChooser.showOpenDialog(null);
if(file != null){
initPlayer(file.toURI().toString());
}
这是方法initPlayer:
private void initPlayer (String uri) {
if (uri == null)
return;
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer = null;
}
Media media = new Media(uri);
mediaPlayer = new MediaPlayer(media);
mediaPlayer.setAutoPlay(true);
mediaView = new MediaView(mediaPlayer);
mediaPlayer.setOnReady(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
}
});
}
这是我在场景构建器中创建的视图中的代码的一部分:
<Pane layoutX="80.0" layoutY="14.0" prefHeight="480.0" prefWidth="640.0">
<MediaView fx:id="mediaView" fitHeight="480.0" fitWidth="640.0" />
</Pane>
当我选择文件时,我听到声音,但我看不到视频。这段代码有什么问题?我缺少什么?
答案 0 :(得分:5)
MediaView
实例由FXMLLoader
创建,并在您加载FXML文件时放在Pane
中。
您不需要创建新的MediaView
,当您这样做时,它不会附加到场景中,这就是您无法看到任何内容的原因。
而不是:
mediaView = new MediaView(mediaPlayer);
写:
mediaView.setMediaPlayer(mediaPlayer);
答案 1 :(得分:1)
如果您只听到声音并且您使用的是Windows XP计算机,则可能会丢失编解码器。
请参阅http://docs.oracle.com/javafx/2/system_requirements_2-2/jfxpub-system_requirements_2-2.htm
或者你可以查看错误播放器提供的内容,如果有的话
mediaPlayer.setOnError(new Runnable() {
@Override
public void run() {
String message = mediaPlayer.errorProperty().get().getMessage();
System.out.println(message);
}
});
答案 2 :(得分:0)
在您的Fxml中,您需要
<FlowPane alignment="CENTER" columnHalignment="CENTER" layoutX="9.0" layoutY="48.0" AnchorPane.bottomAnchor="5.0" AnchorPane.leftAnchor="9.0" AnchorPane.rightAnchor="5.0" AnchorPane.topAnchor="48.0">
<children>
<MediaView fx:id="mediaView">
</MediaView>
</children>
</FlowPane>
并在你的控制器中:
@FXML private MediaPlayer mediaPlayer;
@FXML private Duration duration;
@FXML private MediaView mediaView;
....
@Override
public void initialize(URL url, ResourceBundle rb) {
try {
init();
} catch (MalformedURLException ex) {
Logger.getLogger(MainOnlineController.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void init() throws MalformedURLException {
....
mediaPlayer = new MediaPlayer(media);
mediaPlayer.setAutoPlay(true);
mediaView.setMediaPlayer(mediaPlayer);
mediaPlayer.setOnPlaying(new Runnable() {
public void run() {
if (stopRequested) {
mediaPlayer.pause();
stopRequested = false;
} else {
playButton.setText("||");
}
}
});
...other methods for mediaPlayer