Javafx 简明教程

JavaFX - Playing Video

Video 是视觉沟通的一种媒介。在我们的日常生活中,我们可以在娱乐业、新闻机构、教育平台和许多其他领域看到它的应用。例如,我们可以在下图中看到 YouTube 视频播放器:

video sample

Playing Video in JavaFX

若要在 JavaFX 中播放视频,我们需要将其嵌入应用程序中。有不同的视频格式可用,其中 JavaFX 仅支持 MPEG-4 (简称 mp4)和 FLV 这两种格式。请按照下列步骤将视频嵌入 JavaFX 应用程序:

  1. 首先,实例化包 javafx.scene.mediaMedia 类,方法是传递视频文件的路径。

  2. 接下来,通过将 Media 对象作为参数值传递给其构造函数,创建一个 MediaPlayer 对象。它将使媒体能够在 JavaFX 应用程序中播放。

  3. 然后,通过将 MediaPlayer 对象作为参数值传递给其构造函数,实例化 MediaView 类。这样做将允许 JavaFX 应用程序显示视频。

  4. 最后,创建任意布局窗格并设置场景和舞台,使其具有所需的尺寸。

Example

以下 JavaFX 程序演示了如何将视频嵌入 JavaFX 应用程序中。将此代码保存到名为 Javafx_Video.java 的文件中。

import java.io.File;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;
public class Javafx_Video extends Application {
   @Override
   public void start(Stage stage) {
      // Passing the video file to the File object
      File videofile = new File("sampleTP.mp4");
      // creating a Media object from the File Object
      Media videomedia = new Media(videofile.toURI().toString());
      // creating a MediaPlayer object from the Media Object
      MediaPlayer mdplayer = new MediaPlayer(videomedia);
      // creating a MediaView object from the MediaPlayer Object
      MediaView viewmedia = new MediaView(mdplayer);
      //setting the fit height and width of the media view
      viewmedia.setFitHeight(455);
      viewmedia.setFitWidth(500);
      // creating video controls using the buttons
      Button pause = new Button("Pause");
      Button resume = new Button("Resume");
      // creating an HBox
      HBox box = new HBox(20, pause, resume);
      box.setAlignment(Pos.CENTER);
      // function to handle play and pause buttons
      pause.setOnAction(act -> mdplayer.pause());
      resume.setOnAction(act -> mdplayer.play());
      // creating the root
      VBox root = new VBox(20);
      root.setAlignment(Pos.CENTER);
      root.getChildren().addAll(viewmedia, box);
      Scene scene = new Scene(root, 400, 400);
      stage.setScene(scene);
      stage.setTitle("Example of Video in JavaFX");
      stage.show();
   }
   public static void main(String[] args) {
      launch(args);
   }
}

要从命令提示符编译并执行已保存的 Java 文件,请使用以下命令−

javac --module-path %PATH_TO_FX% --add-modules javafx.controls,javafx.media Javafx_Video.java
java --module-path %PATH_TO_FX% --add-modules javafx.controls,javafx.media Javafx_Video

当我们执行上述代码时,它将生成以下输出。

video example