如何在 Java Swing 应用程序中播放 MP4 视频
How To Play MP4 Video In Java Swing App
有谁知道我可以在 JPanel 中播放 .mp4 视频文件的方法吗?
我尝试过使用 JMF 和 .avi 文件,但没有成功,现在我对播放视频文件这样简单的任务变得如此乏味感到困惑和沮丧。
那里的任何人都请阐明我可以走的路,我将不胜感激。
我听说过 VLCJ,但问题是我不能保证每台机器 运行 这个应用程序都会安装 VLC 播放器。有什么办法可以在分发文件夹中捆绑 VLC 播放器吗?
最初,我们使用的视频是在 Vimeo 上,但事实证明,由于缺乏 API 支持,嵌入它几乎是不可能的,我想好吧,我会在本地播放它,然后甚至现在越来越难了。
感谢@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 的构造函数中调用它以在应用程序启动时触发它。
带有 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);
}
Class 媒体控制
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);
}
}
}
有谁知道我可以在 JPanel 中播放 .mp4 视频文件的方法吗? 我尝试过使用 JMF 和 .avi 文件,但没有成功,现在我对播放视频文件这样简单的任务变得如此乏味感到困惑和沮丧。
那里的任何人都请阐明我可以走的路,我将不胜感激。
我听说过 VLCJ,但问题是我不能保证每台机器 运行 这个应用程序都会安装 VLC 播放器。有什么办法可以在分发文件夹中捆绑 VLC 播放器吗?
最初,我们使用的视频是在 Vimeo 上,但事实证明,由于缺乏 API 支持,嵌入它几乎是不可能的,我想好吧,我会在本地播放它,然后甚至现在越来越难了。
感谢@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 的构造函数中调用它以在应用程序启动时触发它。
带有 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);
}
Class 媒体控制
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);
}
}
}