I have created a media player method is javafx which is called upon startup (below is the media player). My problem is that this pauses whenever I interact with a scroll pane by dragging or by zooming the player pauses and does not start again. Why is this the case and how may I fix this(included full application if you would to try it).
Method(Live code)
private static void MusicPlayer() {
if(musicList.peek() == null)
{
return;
}
MediaPlayer mediaPlayer = new MediaPlayer(new Media(new File(musicList.poll()).toURI().toString()));
mediaPlayer.setOnReady(() -> {
mediaPlayer.play();
mediaPlayer.setOnEndOfMedia(() -> {
mediaPlayer.dispose();
MusicPlayer();
});
});
}
Minimal
package minimalist;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
public class Minimal extends Application{
private static Queue<String> musicList = new LinkedList<String>();
public static void main(String[] args) throws IOException {
List<String> result = Files.find(Paths.get(".\\music"), 100,
(p, a) -> p.toString().toLowerCase().endsWith(".mp3"))
.map(path -> path.toString())
.collect(Collectors.toList());
for(int a = 0; a < result.size(); a++)
{
musicList.add(result.get(a));
}
MusicPlayer();
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
ScrollPane scrollpane = new ScrollPane();
Image image = new Image("https://upload.wikimedia.org/wikipedia/commons/7/70/Kusatma_Zonaro.jpg");
ImageView imageView = new ImageView(image);
scrollpane.setContent(imageView);
scrollpane.setPannable(true);
Scene scene = new Scene(new StackPane(scrollpane));
primaryStage.setScene(scene);
primaryStage.setFullScreen(true);
primaryStage.show();
}
private static void MusicPlayer() {
if(musicList.peek() == null)
{
return;
}
MediaPlayer mediaPlayer = new MediaPlayer(new Media(new File(musicList.poll()).toURI().toString()));
mediaPlayer.setOnReady(() -> {
mediaPlayer.play();
mediaPlayer.setOnEndOfMedia(() -> {
mediaPlayer.dispose();
MusicPlayer();
});
});
}
}
This all seems to behave in something of a fragile manner.
I would not recommend launching the media player from the main method. The documentation is a bit lacking on threading policy for MediaPlayer, but since you are launching a regular JavaFX application it would seem sensible to follow the usual rules and only call methods on it from the JavaFX Application Thread. On my system, I was unable to get any music playing the way you had it set up.
I also had sporadic issues getting it to start playing after changing that; I guessed that maybe I was leaving system resources tied up after exiting, so I modified the code to ensure the player was disposed when the application ended. After both those changes, it behaved as expected. At no point though did I have any issues associated with user input; my guess is that these are caused by launching the media player from the main thread instead of from the FX Application Thread, and are probably system-dependent.
Here's the code that worked fine for me. I also cleaned up some of the redundancy in your code (iterating through Paths to convert them to Strings which you then convert back to Files so you can convert to a string representation of a URL seems somewhat circuitous; you also create a completely unnecessary list in that process, etc) and renamed things so that it abides by proper naming conventations):
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.Queue;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
public class Minimal extends Application{
private Queue<Path> musicList = new LinkedList<>();
private MediaPlayer mediaPlayer ;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
// Everyone should have this album. Edit the path if your musical taste is poor.
Files.find(Paths.get(System.getProperty("user.home"),"Music/iTunes/iTunes Media/Music/Thievery Corporation/Saudade/"), 100,
(p, a) -> p.toString().toLowerCase().endsWith(".m4a"))
.forEach(musicList::add);
playMusic();
ScrollPane scrollpane = new ScrollPane();
Image image = new Image("https://upload.wikimedia.org/wikipedia/commons/7/70/Kusatma_Zonaro.jpg");
ImageView imageView = new ImageView(image);
scrollpane.setContent(imageView);
scrollpane.setPannable(true);
Scene scene = new Scene(new StackPane(scrollpane));
primaryStage.setScene(scene);
primaryStage.setFullScreen(true);
primaryStage.show();
}
#Override
public void stop() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.dispose();
}
}
private void playMusic() {
if(musicList.peek() == null)
{
return;
}
mediaPlayer = new MediaPlayer(new Media(musicList.poll().toUri().toString()));
mediaPlayer.setOnReady(() -> {
mediaPlayer.play();
mediaPlayer.setOnEndOfMedia(() -> {
mediaPlayer.dispose();
playMusic();
});
});
}
}
Related
My friend and I have been working on a Java project to create a simple media player using the Media, MediaPlayer, and MediaView classes. However, from the start we've had issues successfully opening the video that we're using as a test file. After many angry runtime exceptions, we finally figured out that the source of our problem was the String being passed into each object (Media needs a String that represents the File Path in a URI format). After some modifications, we found that the following URI worked on my computer to open the File:
Media m = new Media("file:///C:/Users/mewww/Google%20Drive/Java/SmartPlay/EXO-MonsterMV.mp4");
MediaPlayer mp = new MediaPlayer(m);
MediaView mv = new MediaView(mp);
However, we later tried to implement an Open method that would allow the user to choose which File (as a File object) they wanted to play. When we did this, we used the following to open the file:
File currentFile = new File(null);
FileChooser fc = new FileChooser();
fc.setTitle("Open");
currentFile = fc.showOpenDialog(null);
Media m = new Media(currentFile.toURI().toString());
MediaPlayer mp = new MediaPlayer(m);
MediaView mv = new MediaView(mp);
This started giving us runtime exceptions again and so we used a println into the console to find out what the problem was. The string being used was now two "/"s short of what it was supposed to be as:
"file:/C:/Users/mewww/Google%20Drive/Java/SmartPlay/EXO-MonsterMV.mp4"
However, even after modifying the string, we still received the same runtime error as soon as the file was selected:
Exception in Application start method
java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
We then commented the whole Open method out and went back to our original code, but continue to receive the same errors.
Our full code is available here:
SmartPlay class
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.paint.Color;
import java.io.File;
import javafx.stage.FileChooser;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.application.Platform;
public class SmartPlay extends Application {
File currentFile;
Scene scene;
#Override
public void start(Stage primary) {
primary.setTitle("SmartPlay");
selectCurrentFileToOpen();
//Player(currentFile.toURI().toString().substring(0,5)+"//"+currentFile.toURI().toString().substring(5));
Player player = new Player("file:///C:/Users/mewww/Google%20Drive/Java/SmartPlay/EXOMonsterMV.mp4");
scene = new Scene(player, 720, 480, Color.BLACK);
player.setTop(makeMenus());
primary.setScene(scene);
primary.show();
}
private MenuBar makeMenus() {
MenuBar mb = new MenuBar();
Menu fileMenu = new Menu("File");
MenuItem openItem = new MenuItem("Open...");
openItem.setOnAction(e -> {
selectCurrentFileToOpen();
scene.setRoot(new Player(currentFile.toURI()));
});
MenuItem quitItem = new MenuItem("Quit");
quitItem.setOnAction(e -> Platform.exit());
fileMenu.getItems().addAll(openItem, quitItem);
return mb;
}
public boolean selectCurrentFileToOpen() {
FileChooser fc = new FileChooser();
fc.setTitle("Open");
currentFile = fc.showOpenDialog(null);
return true;
}
public void stop() {
}
public static void main(String[] args) {
launch(args);
}
}
Player class
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import java.net.URI;
public class Player extends BorderPane {
Media m;
MediaPlayer mp;
MediaView mv;
Pane p;
MediaBar bar;
public Player(String file) {
m = new Media(file);
mp = new MediaPlayer(m);
mv = new MediaView(mp);
p = new Pane();
p.getChildren().addAll(mv);
setCenter(p);
bar = new MediaBar(mp);
setBottom(bar);
setStyle("-fx-background-color:#cccccc");
mp.play();
}
}
MediaBar class
import javafx.scene.layout.HBox;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.media.MediaPlayer;
import javafx.scene.layout.Priority;
import javafx.scene.control.Slider;
import javafx.scene.control.Label;
import javafx.scene.control.Button;
import javafx.util.Duration;
public class MediaBar extends HBox {
Slider time = new Slider();
Slider vol = new Slider();
Button playButton = new Button("Pause");
Button halfSpeed = new Button("0.5x");
Button normalSpeed = new Button("1.0x");
Button doubleSpeed = new Button("2.0x");
Label volume = new Label("Volume: ");
Label nowTime;
MediaPlayer player;
public MediaBar(MediaPlayer play) {
player = play;
setAlignment(Pos.CENTER);
setPadding(new Insets(5,10,5,10));
vol.setPrefWidth(70);
vol.setMinWidth(30);
vol.setValue(100);
nowTime = new Label(formatTime(player.getCurrentTime()) + "/" + formatTime(player.getTotalDuration()));
HBox.setHgrow(time, Priority.ALWAYS);
playButton.setPrefWidth(30);
getChildren().addAll(playButton,time,nowTime,volume,vol);
}
public static String formatTime(Duration duration) { //StackOverflow: Jon Skeet
long seconds = (long) duration.toSeconds();
long absSeconds = Math.abs(seconds);
String positive = String.format(
"%d:%02d:%02d",
//absSeconds / 3600,
(absSeconds % 3600) / 60,
absSeconds % 60);
return seconds < 0 ? "-" + positive : positive;
}
}
So I ran your code in command line and I was able to get a more specific debug error. So it seems like the time formatting you do in your MediaBar is causing the error. I don't know exactly what you are trying to do with that but the way you format the time is incorrect. If you comment it out as well as the other things you use to add the time formatting the URI path will be correct and your video should run fine. I know that for the formatting you are missing a '%02d'. As for what you are formatting I am not too sure so I cannot help you there.
Context
I just started to learn JavaFX so I'm developing a program to discover it. The program I'm on needs a array, so I used ObservableList. But here is the problem, the items I add to the list are only accessible from the function itself.
Here is the situation :
package fr.cartes;
import fr.cartes.model.MapModel;
import fr.cartes.view.ListMapsController;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
import java.util.ArrayList;
public class MainApp extends Application {
private Stage primaryStage;
private ObservableList<MapModel> maps = FXCollections.observableArrayList();
public static void main(String[] args){
launch(args);
}
public void start(Stage primaryStage) throws Exception {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("/!\\ Explorateur /!\\");
this.primaryStage.setAlwaysOnTop(true);
initializationOfProgram();
}
public void initializationOfProgram(){
initializeListMaps();
maps.add(new MapModel("Les Etats-Unis d'Amérique", "EU.jpg"));
maps.add(new MapModel("La France d'aujourdh'ui", "FR.jpg"));
for(MapModel mapModel : maps){
System.out.println(mapModel.getMapName());
}
}
public void initializeListMaps(){
for(MapModel map : maps){
System.out.println(map.getMapName());
}
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("view/ListMaps.fxml"));
Scene scene = new Scene(loader.load());
primaryStage.setScene(scene);
primaryStage.show();
ListMapsController controller = new ListMapsController();
controller.setMainApp(this);
controller.loadMapsOnListView(maps);
}catch(IOException exception){exception.printStackTrace();}
}
public ObservableList<MapModel> getMapsLists(){
return maps;
}
}
For example, if I put a println() test in the initializationOfProgram(), I will have "Les Etats-Unis d'Amérique" and "La France d'aujourd'hui" written on the console, but if I do this println() test in initializeListMaps(), it won't display anything.
Am I missing something obvious here ? Can you help me ?
This question already has answers here:
Standard concise way to copy a file in Java?
(16 answers)
Closed 6 years ago.
I am making program where user can choose image with FileChooser and display it in program. But i want to save all the images in my folder. I want to store all the images there. So is there any option if user choose image which is on desktop to make a copy of that image and paste it in my folder?
Well im not entirely sure about your implementation and how you are presenting the opened image in your program but taking oracles example from here : http://docs.oracle.com/javafx/2/ui_controls/file-chooser.htm
its fairly simple to make the program copy the selected files to a certain direction using javaNIO:
private void openFile(File file) {
try {
File dest = new File("C:\\Users\\yourProfile\\Desktop"); //any location
Files.copy(file.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ex) {
Logger.getLogger(
FileChooserSample.class.getName()).log(
Level.SEVERE, null, ex
);
}
}
You can test this with the example application i linked earlier:
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
public final class FileChooserSample extends Application {
private Desktop desktop = Desktop.getDesktop();
#Override
public void start(final Stage stage) {
stage.setTitle("File Chooser Sample");
final FileChooser fileChooser = new FileChooser();
final Button openButton = new Button("Open a Picture...");
final Button openMultipleButton = new Button("Open Pictures...");
openButton.setOnAction(
new EventHandler<ActionEvent>() {
#Override
public void handle(final ActionEvent e) {
File file = fileChooser.showOpenDialog(stage);
if (file != null) {
openFile(file);
}
}
});
openMultipleButton.setOnAction(
new EventHandler<ActionEvent>() {
#Override
public void handle(final ActionEvent e) {
List<File> list =
fileChooser.showOpenMultipleDialog(stage);
if (list != null) {
for (File file : list) {
openFile(file);
}
}
}
});
final GridPane inputGridPane = new GridPane();
GridPane.setConstraints(openButton, 0, 0);
GridPane.setConstraints(openMultipleButton, 1, 0);
inputGridPane.setHgap(6);
inputGridPane.setVgap(6);
inputGridPane.getChildren().addAll(openButton, openMultipleButton);
final Pane rootGroup = new VBox(12);
rootGroup.getChildren().addAll(inputGridPane);
rootGroup.setPadding(new Insets(12, 12, 12, 12));
stage.setScene(new Scene(rootGroup));
stage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
private void openFile(File file) {
try {
desktop.open(file);
File dest = new File("C:\\Users\\yourprofile\\Desktop");
Files.copy(file.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ex) {
Logger.getLogger(
FileChooserSample.class.getName()).log(
Level.SEVERE, null, ex
);
}
}
}
You just have to modify the directory, note however there are many ways and implementations of copying files depending on which version of java you are using and whether or not you are using other libraries such as apache io.
Other links that may be useful if you are using a standard file method :
JavaPractices JavaCodeGeek StackOverflow
Hope that helps in anyway :) good luck with your program.
Basically my code is like this:
fileOpener.setOnAction(
new EventHandler<ActionEvent>() {
#Override
public void handle(final ActionEvent e) {
myFileList.add(openMusicTracks.showOpenDialog(window));
System.out.println(myFileList.getName(0)); //prints file name so I know this works
}
});
I want the add method (that's inside of the EventHandler) to actually edit the arraylist for everywhere else so that later when I reference it in
ObservableList<String> playList = FXCollections.observableArrayList ();
for(int i = 0; i < myFileList.size(); i++) {
playList.add(i, myFileList.get(i).getName());
System.out.println(myFileList.getName(0)); //doesn't print the file name, so I know this doesn't work.
}
the arraylist won't be empty. How do I do this? I'm sorry if there's a more elegant way to word this, but I have honestly no idea how to research this, I've tried. Thanks.
A simple example which shows how can an ArrayList be shared between methods.
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.List;
public class Main extends Application {
private List<String> list = new ArrayList<>();
#Override
public void start(Stage primaryStage) {
Button add = new Button("Add");
Button display = new Button("Show");
// Add Items
add.setOnAction(event -> list.add("Item"));
// Display Items
display.setOnAction(e -> {
printAndClear();
});
VBox root = new VBox(10, add, display);
root.setAlignment(Pos.CENTER);
Scene scene = new Scene(root, 200, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
private void printAndClear() {
list.forEach(System.out::println);
list.clear();
}
public static void main(String[] args) {
launch(args);
}
}
I need to create a video player using Java for my project. I have already checked many examples on the Internet. Some of them run, but do not show any screen, I can only hear the sound of the video. Please help me solve this...
I am using the below import
import javax.media.*;
EDIT:
Below is the code that i use:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.media.*;
public class MediaPlayerDemo extends JFrame
{
private Player player;
private File file;
public MediaPlayerDemo()
{
super( "Demonstrating the Java Media Player" );
JButton openFile = new JButton( "Open file to play" );
openFile.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
openFile();
createPlayer();
}
});
getContentPane().add( openFile, BorderLayout.NORTH );
setSize( 300, 300 );
show();
}
private void openFile()
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
int result = fileChooser.showOpenDialog( this );
// user clicked Cancel button on dialog
if ( result == JFileChooser.CANCEL_OPTION )
file = null;
else
file = fileChooser.getSelectedFile();
}
private void createPlayer()
{
if ( file == null )
return;
removePreviousPlayer();
try
{
// create a new player and add listener
player = Manager.createPlayer( file.toURL() );
player.addControllerListener( new EventHandler() );
player.start(); // start player
}
catch ( Exception e )
{
JOptionPane.showMessageDialog( this, "Invalid file or location", "Error loading file",
JOptionPane.ERROR_MESSAGE );
}
}
private void removePreviousPlayer()
{
if ( player == null )
return;
player.close();
Component visual = player.getVisualComponent();
Component control = player.getControlPanelComponent();
Container c = getContentPane();
if ( visual != null )
c.remove( visual );
if ( control != null )
c.remove( control );
}
public static void main(String args[])
{
MediaPlayerDemo app = new MediaPlayerDemo();
app.addWindowListener( new WindowAdapter()
{
public void windowClosing( WindowEvent e )
{
System.exit(0);
}
});
}
// inner class to handler events from media player
private class EventHandler implements ControllerListener
{
public void controllerUpdate( ControllerEvent e )
{
if ( e instanceof RealizeCompleteEvent )
{
Container c = getContentPane();
// load Visual and Control components if they exist
Component visualComponent = player.getVisualComponent();
if ( visualComponent != null )
c.add( visualComponent, BorderLayout.CENTER );
Component controlsComponent = player.getControlPanelComponent();
if ( controlsComponent != null )
c.add( controlsComponent, BorderLayout.SOUTH );
c.doLayout();
}
}
}
}
I used vlcj and it worked smoothly. It's java binding to vlcj player and the good thing that you don't have to provide any drives since vlcj already includes all of them in binary distribution.
Give it a go, there is example of already working player built for you!
Try a JavaFX Mediaplayer:
Usable Codecs:
Audio: MP3; AIFF containing uncompressed PCM; WAV containing uncompressed PCM; MPEG-4 multimedia container with Advanced Audio Coding (AAC) audio
Video: FLV containing VP6 video and MP3 audio; MPEG-4 multimedia
container with H.264/AVC (Advanced Video Coding) video compression .
Here an example from Oracle:
import javafx.application.Application;
import javafx.collections.ListChangeListener;
import javafx.collections.MapChangeListener;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.media.Media;
import javafx.scene.media.MediaView;
import javafx.scene.media.Track;
import javafx.stage.Stage;
/**
* A sample media player which loops indefinitely over the same video
*/
public class MediaPlayer extends Application {
private static final String MEDIA_URL = "http://someserver/somedir/somefile.mp4";
private static String arg1;
#Override public void start(Stage stage) {
stage.setTitle("Media Player");
// Create media player
Media media = new Media((arg1 != null) ? arg1 : MEDIA_URL);
javafx.scene.media.MediaPlayer mediaPlayer = new javafx.scene.media.MediaPlayer(media);
mediaPlayer.setAutoPlay(true);
mediaPlayer.setCycleCount(javafx.scene.media.MediaPlayer.INDEFINITE);
// Print track and metadata information
media.getTracks().addListener(new ListChangeListener<Track>() {
public void onChanged(Change<? extends Track> change) {
System.out.println("Track> "+change.getList());
}
});
media.getMetadata().addListener(new MapChangeListener<String,Object>() {
public void onChanged(MapChangeListener.Change<? extends String, ? extends Object> change) {
System.out.println("Metadata> "+change.getKey()+" -> "+change.getValueAdded());
}
});
// Add media display node to the scene graph
MediaView mediaView = new MediaView(mediaPlayer);
Group root = new Group();
Scene scene = new Scene(root,800,600);
root.getChildren().add(mediaView);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
if (args.length > 0) {
arg1 = args[0];
}
Application.launch(args);
}
}
https://blogs.oracle.com/javafx/entry/mpeg_4_multimedia_support_in
Here is the working code.
package New;
import java.net.URL;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaPlayer.Status;
import javafx.scene.media.MediaView;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class FxMediaExample2 extends Application {
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(Stage stage) {
// Locate the media content in the CLASSPATH
URL mediaUrl = getClass().getResource("Test.mp4");
String mediaStringUrl = mediaUrl.toExternalForm();
// Create a Media
Media media = new Media(mediaStringUrl);
// Create a Media Player
final MediaPlayer player = new MediaPlayer(media);
// Automatically begin the playback
player.setAutoPlay(true);
// Create a 400X300 MediaView
MediaView mediaView = new MediaView(player);
mediaView.setFitWidth(400);
mediaView.setFitHeight(300);
mediaView.setSmooth(true);
mediaView.setLayoutX(200);
mediaView.setLayoutY(200);
// Create the DropShadow effect
DropShadow dropshadow = new DropShadow();
dropshadow.setOffsetY(5.0);
dropshadow.setOffsetX(5.0);
dropshadow.setColor(Color.RED);
mediaView.setEffect(dropshadow);
Rectangle rect4 = new Rectangle(35, 55, 95, 25);
rect4.setFill(Color.RED);
rect4.setStroke(Color.BLACK);
rect4.setStrokeWidth(1);
// Create the HBox
// HBox controlBox = new HBox(5, null, null);
// Create the VBox
VBox root = new VBox(1, mediaView);
GridPane gridpane = new GridPane();
gridpane.setPadding(new Insets(95));
gridpane.setHgap(1);
gridpane.setVgap(10);
GridPane.setHalignment(rect4, HPos.CENTER);
Group grp = new Group();
gridpane.add(root, 1, 1);
grp.getChildren().add(gridpane);
// Create the Scene
Scene scene = new Scene(grp);
// Add the scene to the Stage
stage.setScene(scene);
// Set the title of the Stage
stage.setTitle("A simple Media Example");
// Display the Stage
stage.show();
}
}
Java Media Framework can be used to create multimedia applications like video and audio players.