How To Play MP4 Video In Java Swing App

Zana Daniel :

Does anyone know any way I can play an .mp4 video file in a JPanel? I have tried JMF with .avi file but found no success and now I'm baffled and frustrated at how such a simple task of playing a video file is becoming so tedious.

Anyone out there please shed some light on what path I could take and I would greatly appreciate it.

I've heard of VLCJ but the issue is I can't guarantee that every machine running this app will have VLC player installed. Is there a way I can bundle VLC player in the distribution folder?

Originally, the video we're using is on Vimeo but it turns out it's practically impossible to embed it due a lack of API support and I thought okay I will just play it locally and then even that is becoming so difficult now.

Zana Daniel :

Thanks to @VGR for bringing JavaFX to my attention, I just integrated a JFXPanel into a JPanel of where I wanted the video to be. It's working perfectly fine in my case since it's a simple screen with one video to play.

Here's the full code snippet below:

private void getVideo(){
    final JFXPanel VFXPanel = new JFXPanel();

    File video_source = new File("tutorial.mp4");
    Media m = new Media(video_source.toURI().toString());
    MediaPlayer player = new MediaPlayer(m);
    MediaView viewer = new MediaView(player);

    StackPane root = new StackPane();
    Scene scene = new Scene(root);

    // center video position
    javafx.geometry.Rectangle2D screen = Screen.getPrimary().getVisualBounds();
    viewer.setX((screen.getWidth() - videoPanel.getWidth()) / 2);
    viewer.setY((screen.getHeight() - videoPanel.getHeight()) / 2);

    // resize video based on screen size
    DoubleProperty width = viewer.fitWidthProperty();
    DoubleProperty height = viewer.fitHeightProperty();
    width.bind(Bindings.selectDouble(viewer.sceneProperty(), "width"));
    height.bind(Bindings.selectDouble(viewer.sceneProperty(), "height"));
    viewer.setPreserveRatio(true);

    // add video to stackpane
    root.getChildren().add(viewer);

    VFXPanel.setScene(scene);
    //player.play();
    videoPanel.setLayout(new BorderLayout());
    videoPanel.add(VFXPanel, BorderLayout.CENTER);
}

Once the getVideo() function is made, I called it in the constructor of the JFrame to trigger it on the applications launch.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=79894&siteId=1