如何在Java Swing应用程序中播放MP4视频

时间:2018-08-27 12:05:35

标签: java video jframe jpanel mp4

有人知道我可以在JPanel中播放.mp4视频文件的任何方式吗? 我曾尝试将JMF与.avi文件一起使用,但没有成功,现在,我对如此简单的视频文件播放任务变得如此乏味感到困惑和沮丧。

任何人都请向我阐明我可以走什么路,我将不胜感激。

我听说过VLCJ,但问题是我不能保证每台运行此应用程序的计算机都将安装VLC播放器。有什么方法可以将VLC播放器捆绑在分发文件夹中?

最初,我们正在使用的视频是在Vimeo上发布的,但是由于缺乏API支持,事实证明几乎不可能嵌入该视频,我想我可以在本地播放它,即使现在变得如此困难。

2 个答案:

答案 0 :(得分:3)

由于@VGR引起了我对JavaFX的关注,我只是将JFXPanel集成到了我想要视频放置的JPanel中。就我而言,它工作得很好,因为它是一个可以播放一个视频的简单屏幕。

以下是完整的代码段:

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);
}

一旦创建了getVideo()函数,我就会在JFrame的构造函数中调用它,以在应用程序启动时触发它。

答案 1 :(得分:0)

具有MediaControl的播放器

public class MainFrame {

private JFrame frmPlayerJava;
private JFXPanel videoPanel;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                MainFrame window = new MainFrame();
                window.frmPlayerJava.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
    });
}

public MainFrame() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frmPlayerJava = new JFrame();
    frmPlayerJava.setTitle("Player Java");
    frmPlayerJava.setBounds(100, 100, 1260, 782);
    frmPlayerJava.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frmPlayerJava.getContentPane().setLayout(null);
    videoPanel = new JFXPanel();
    videoPanel.setBorder(new LineBorder(new Color(0, 0, 0), 2));
    videoPanel.setBounds(714, 309, 509, 317);
    frmPlayerJava.getContentPane().add(videoPanel);
    
    JLabel Title = new JLabel("Metus Player Java");
    Title.setHorizontalAlignment(SwingConstants.CENTER);
    Title.setFont(new Font("Tahoma", Font.PLAIN, 24));
    Title.setBounds(502, 11, 289, 42);
    frmPlayerJava.getContentPane().add(Title);
    
    
    JButton btnNewButton = new JButton("Play");
    btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 23));
    btnNewButton.setBounds(870, 637, 228, 79);
    frmPlayerJava.getContentPane().add(btnNewButton);

    
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
                getVideo();
        }
    });
}

private void getVideo(){
    File video_source = new File("video.mp4");
    Media m = new Media(video_source.toURI().toString());
    //Media m = new Media("https://www.youtube.com/embed/qzW6mgfY5X4");
    MediaPlayer player = new MediaPlayer(m);
    player.play();
    MediaControl mediaControl = new MediaControl(player);
    
    StackPane root = new StackPane();
    Scene scene = new Scene(root);
    scene.setRoot(mediaControl);
    
    // add video to stackpane
    videoPanel.setScene(scene);
    
}

MediaControl类

import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaPlayer.Status;
import javafx.scene.media.MediaView;
import javafx.util.Duration;

public class MediaControl extends BorderPane {
    this.mp = mp;
    setStyle("-fx-background-color: #bfc2c7;");
    mediaView = new MediaView(mp);
    StackPane mvPane = new StackPane() {
    };
    
    mvPane.getChildren().add(mediaView);
    mvPane.setStyle("-fx-background-color: black;");
    mediaView.fitWidthProperty().bind(mvPane.widthProperty());
    mediaView.fitHeightProperty().bind(mvPane.heightProperty());
    mediaView.setPreserveRatio(true);
    setCenter(mvPane);

    mediaBar = new HBox();
    mediaBar.setAlignment(Pos.CENTER);
    mediaBar.setPadding(new Insets(5, 10, 5, 10));
    BorderPane.setAlignment(mediaBar, Pos.CENTER);

    final Button playButton = new Button(">");

    playButton.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            Status status = mp.getStatus();

            if (status == Status.UNKNOWN || status == Status.HALTED) {
                // don't do anything in these states
                return;
            }

            if (status == Status.PAUSED
                    || status == Status.READY
                    || status == Status.STOPPED) {
                // rewind the movie if we're sitting at the end
                if (atEndOfMedia) {
                    mp.seek(mp.getStartTime());
                    atEndOfMedia = false;
                }
                mp.play();
            } else {
                mp.pause();
            }
        }
    });
    mp.currentTimeProperty().addListener(new InvalidationListener() {
        public void invalidated(Observable ov) {
            updateValues();
        }
    });

    mp.setOnPlaying(new Runnable() {
        public void run() {
            if (stopRequested) {
                mp.pause();
                stopRequested = false;
            } else {
                playButton.setText("||");
            }
        }
    });

    mp.setOnPaused(new Runnable() {
        public void run() {
            System.out.println("onPaused");
            playButton.setText(">");
        }
    });

    mp.setOnReady(new Runnable() {
        public void run() {
            duration = mp.getMedia().getDuration();
            System.out.println("Duration: "+duration);
            updateValues();
        }
    });

    mp.setCycleCount(repeat ? MediaPlayer.INDEFINITE : 1);
    mp.setOnEndOfMedia(new Runnable() {
        public void run() {
            System.out.println("Entre");
            if (!repeat) {
                playButton.setText(">");
                stopRequested = true;
                atEndOfMedia = true;
            }
        }
    });

    mediaBar.getChildren().add(playButton);
    // Add spacer
    Label spacer = new Label("   ");
    mediaBar.getChildren().add(spacer);

    // Add Time label
    Label timeLabel = new Label("Tiempo: ");
    mediaBar.getChildren().add(timeLabel);

    // Add time slider
    timeSlider = new Slider();
    HBox.setHgrow(timeSlider, Priority.ALWAYS);
    timeSlider.setMinWidth(50);
    timeSlider.setMaxWidth(Double.MAX_VALUE);
    timeSlider.valueProperty().addListener(new InvalidationListener() {
        public void invalidated(Observable ov) {
            if (timeSlider.isValueChanging()) {
                // multiply duration by percentage calculated by slider position
                mp.seek(duration.multiply(timeSlider.getValue() / 100.0));
            }
        }
    });
    mediaBar.getChildren().add(timeSlider);
    
    Label spacer1 = new Label("   ");
    mediaBar.getChildren().add(spacer1);
    
    // Add Play label
    playTime = new Label();
    playTime.setPrefWidth(130);
    playTime.setMinWidth(50);
    mediaBar.getChildren().add(playTime);

    // Add the volume label
    Label volumeLabel = new Label("Vol: ");
    mediaBar.getChildren().add(volumeLabel);

    // Add Volume slider
    volumeSlider = new Slider(0,100,100);
    volumeSlider.setPrefWidth(70);
    volumeSlider.setMaxWidth(Region.USE_PREF_SIZE);
    volumeSlider.setMinWidth(30);
    volumeSlider.valueProperty().addListener(new InvalidationListener() {
        public void invalidated(Observable ov) {
            if (volumeSlider.isValueChanging()) {
                mp.setVolume(volumeSlider.getValue() / 100.0);
            }
        }
    });
    mediaBar.getChildren().add(volumeSlider);

    setBottom(mediaBar);
}

protected void updateValues() {
    if (playTime != null && timeSlider != null && volumeSlider != null) {
        Platform.runLater(new Runnable() {
            public void run() {
                duration = mp.getMedia().getDuration();
                Duration currentTime = mp.getCurrentTime();
                playTime.setText(formatTime(currentTime, duration));
                timeSlider.setDisable(duration.isUnknown());
                if (!timeSlider.isDisabled()
                        && duration.greaterThan(Duration.ZERO)
                        && !timeSlider.isValueChanging()) {
                    timeSlider.setValue(currentTime.divide(duration).toMillis()
                            * 100.0);
                }
                if (!volumeSlider.isValueChanging()) {
                    volumeSlider.setValue((int) Math.round(mp.getVolume()
                            * 100));
                }
            }
        });
    }
}

private static String formatTime(Duration elapsed, Duration duration) {
    int intElapsed = (int) Math.floor(elapsed.toSeconds());
    int elapsedHours = intElapsed / (60 * 60);
    if (elapsedHours > 0) {
        intElapsed -= elapsedHours * 60 * 60;
    }
    int elapsedMinutes = intElapsed / 60;
    int elapsedSeconds = intElapsed - elapsedHours * 60 * 60
            - elapsedMinutes * 60;

    if (duration.greaterThan(Duration.ZERO)) {
        int intDuration = (int) Math.floor(duration.toSeconds());
        int durationHours = intDuration / (60 * 60);
        if (durationHours > 0) {
            intDuration -= durationHours * 60 * 60;
        }
        int durationMinutes = intDuration / 60;
        int durationSeconds = intDuration - durationHours * 60 * 60
                - durationMinutes * 60;
        if (durationHours > 0) {
            return String.format("%d:%02d:%02d/%d:%02d:%02d",
                    elapsedHours, elapsedMinutes, elapsedSeconds,
                    durationHours, durationMinutes, durationSeconds);
        } else {
            return String.format("%02d:%02d/%02d:%02d",
                    elapsedMinutes, elapsedSeconds, durationMinutes,
                    durationSeconds);
        }
    } else {
        if (elapsedHours > 0) {
            return String.format("%d:%02d:%02d", elapsedHours,
                    elapsedMinutes, elapsedSeconds);
        } else {
            return String.format("%02d:%02d", elapsedMinutes,
                    elapsedSeconds);
        }
    }
}

enter image description here