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.
Related
I am currently making a program where you can add and delete items from a listview in Java, i want it to be able to automatically save when you add items to the list view and delete items. I am having a hard time figuring out how to do this any help would be greatly appreciated. i am still very new at programming and still trying to figure it all out here is my code i have so far.
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javafx.application.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class LendingLibraryGUI extends Application {
LendingLibrary LendingLibrary = new LendingLibrary(); //Creating an Object to access total numbers of items
MediaItems Media = new MediaItems(); // creating an array of object to access MediaItems class and allowing it to hold 100 items
private ListView<String> library = new ListView<String>();
ObservableList<String> libraryList = FXCollections.<String>observableArrayList("yes","no");
#Override
public void start(Stage primaryStage) throws Exception {
BorderPane display = new BorderPane(); //Main display
GridPane buttons = new GridPane(); //location to display buttons
TextField outPut = new TextField(); //Text field to show inventory
Insets padding = new Insets(10); //creates Insets for padding
buttons.setPadding(padding); //padding around grid pane
buttons.setHgap(10); //Horizontal gap
library.setItems(libraryList);
for (int i =0; i !=4;i++) { //Loop to create Buttons
String[] actionButtons = {"Add","Check Out","Check In","Delete"};//String to store Button names
Button temp = new Button(actionButtons[i]);
temp.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
buttons.add(temp, i, 0); //add buttons to grid pane
GridPane.setHgrow(temp, Priority.ALWAYS);
GridPane.setVgrow(temp, Priority.ALWAYS);
if (temp.getText().equals("Add")) {
temp.setOnAction((e) -> add());
}
else if (temp.getText().equals("Delete")) {
temp.setOnAction((e) -> deleteLibrary());
}
}
outPut.setEditable(false); //no editing
outPut.setFont(Font.font("monospace", FontWeight.BOLD, 20));
outPut.setMinHeight(300);//sets minimum height
display.setTop(library); //sets output in display on top
display.setCenter(buttons); //sets buttons on center
Scene scene = new Scene(display); //creates new scene
primaryStage.setTitle("Lending Library"); //sets title of GUI
primaryStage.setScene(scene); //adds scene to GUI
primaryStage.setMinHeight(400); //Minimum height
primaryStage.setMinWidth(350);//Minimum Width
primaryStage.show();//Displays GUI to user
}
public static void main(String[] args) {
launch(args);
}
private void add() {
inputGUI("Title:");
}
private void inputGUI(String input) {
Stage secondaryStage = new Stage();
BorderPane border = new BorderPane();
VBox titlePane = new VBox(8);
HBox buttonLayout = new HBox(8);
Label lblTitle = new Label(input);
Button save = new Button("Save");
Button close = new Button("Close");
Insets padding = new Insets(10);
TextField txt = new TextField("");
close.setOnAction((e) -> secondaryStage.close());;
save.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
try {
LendingLibrary.save(library);
} catch (IOException e1) {
e1.printStackTrace();
}
if (txt.getText().trim().isEmpty()) {
}
else {
if (input.equals("Title:")) {
Media.setTitle(txt.getText());
secondaryStage.close();
inputGUI("Format:");
}
else if (input.equals("Format:")) {
Media.setFormat(txt.getText());
secondaryStage.close();
addToLibrary();
}
else if (input.equals("Who did you loan this to?")) {
}
else if (input.equals("When did you loan it(date)?")) {
}
}
}
});
buttonLayout.getChildren().addAll(close,save);
titlePane.setPadding(padding);
titlePane.getChildren().addAll(lblTitle,txt,buttonLayout);
border.setCenter(titlePane);
BorderPane.setAlignment(titlePane, Pos.CENTER);
Scene scene = new Scene(border); //creates new scene
secondaryStage.setTitle("Input"); //sets title of GUI
secondaryStage.setScene(scene); //adds scene to GUI
secondaryStage.setMinHeight(200); //Minimum height
secondaryStage.setMinWidth(350);//Minimum Width
secondaryStage.show();//Displays GUI to user
}
private void addToLibrary() {
String total;
total = Media.getTitle();
total = total + " ("+ Media.getFormat() +")";
libraryList.add(total);
library.setItems(libraryList);
}
private void deleteLibrary() {
int selectedItem = library.getSelectionModel().getSelectedIndex();
libraryList.remove(selectedItem);
}
private void checkOut() {
}
}
Any other pointers or advice would be greatly appreciated!
Thanks in advance
edit:
Again im very new just trying to learn basic stuff this isnt something i am going to keep just going through a book and this is something in it that its trying to teach me.
public void save(ListView<String> library) throws IOException {
File file = new File ("LendingLibrary.txt"); //creates text file
PrintWriter output = new PrintWriter(file);
if(file.exists()) { //if the file exists
output.println(library);
output.close();
}
if(!file.exists()) { //if file doesn't exist
System.out.println("Error creating file");
}
}
What you really are interested to save is the data that is presented by the list view, you don't need all the other layout information and stuff as they are statically defined in the application and loaded on each run automatically.
Now, although saving the data in a file and loading it each time you need it can work, it is not usually the best. A better approach is to use a database to store the data of your application in form of relation entities, in this way you have a safer and a more consistent approach to work with. To get yourself started in the topic, you can go on and consult the official reference.
If you want to first try using the file approach, the advice is to save the data in some structured format which is then easy to save and load, or in more proper words serialize/deserialize. For this purpose you can use the json format to store the data in a file, and you can use gson library for example:
Each row of the list view is an object that contains the data.
Reading: Serialize the list of data to json format using the gson and store each of them in a separate line.
Reading: Load the list of strings and deserialize them to the java class using gson.
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();
});
});
}
}
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.
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.
I'm making a playlist based mp3 player using javafx and I got everything working except how to pause/resume a song. I tried simply checking the player.Status()and using that but it didn't work so I stored the time of the song when pause()is clicked, in a Duration pausetime variable and it works that way but only once. What happens is: I click pause(), it works, click play(), it resumes the song but after that the pause button stops doing anything.
Btw I'm using two separate ToggleButton for pause and play because of the style I'm going for.
Here's the part of the code i'm talking about:
public void play(){
if (player != null){
player.stop();
}
if (pausebutton.isSelected()){
pausebutton.setSelected(false); //resume part
slider.setValue(pausetime.toSeconds());
play();
}
this.player = players.get(i);
player.setStartTime(pausetime);
player.play();
slide(i);
csong.setText(playlist.get(i).getName());
player.setOnEndOfMedia(new Runnable(){
#Override public void run(){
if (shuffle.isSelected()){
i = rand.nextInt(players.size() + 1);
}
else{
i++;
}
if(loop.isSelected()){
if (i == players.size()){
i = 0;
}}
list.getSelectionModel().select(i);
play();
}
});
}
public void pause(){
player.pause();
pausetime = player.getCurrentTime();
playbutton.setSelected(false);
}
I have created a very simple mp3 player, which has most (if not all) of the components said above.
It has play and pause toggle buttons, which do work ;)
It has labels updating the time elapsed for the song
It has a sliderbar, which can be used to move forward/backward. It automatically updates on song play.
Complete Code
import javafx.application.Application;
import javafx.beans.property.DoubleProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.text.DecimalFormat;
public class MediaPlayerSample extends Application {
private MediaPlayer player;
private final ToggleButton playButton = new ToggleButton("Play");
private final ToggleButton pauseButton = new ToggleButton("Pause");
private final ToggleGroup group = new ToggleGroup();
private final Label totalDuration = new Label();
private final Label currentDuration = new Label();
private final DecimalFormat formatter = new DecimalFormat("00.00");
private final SliderBar timeSlider = new SliderBar();
private Duration totalTime;
#Override
public void start(Stage primaryStage)
{
//Add a scene
VBox root = new VBox(10);
root.setAlignment(Pos.CENTER);
root.setStyle("-fx-background-color: ANTIQUEWHITE");
HBox playPause = new HBox(playButton, pauseButton);
HBox sliderBox = new HBox(timeSlider, currentDuration, totalDuration);
HBox.setHgrow(sliderBox, Priority.ALWAYS);
root.getChildren().addAll(sliderBox, playPause);
Scene scene = new Scene(root, 300, 100);
Media pick = new Media(getClass().getResource("/delete/abc/abc.mp3").toExternalForm());
player = new MediaPlayer(pick);
// Play the track and select the playButton
player.play();
playButton.setSelected(true);
player.currentTimeProperty().addListener(new ChangeListener<Duration>() {
#Override
public void changed(ObservableValue<? extends Duration> observable, Duration oldValue, Duration newValue) {
timeSlider
.sliderValueProperty()
.setValue(newValue.divide(totalTime.toMillis()).toMillis() * 100.0);
currentDuration.setText(String.valueOf(formatter.format(newValue.toSeconds())));
}
});
player.setOnReady(() -> {
// Set the total duration
totalTime = player.getMedia().getDuration();
totalDuration.setText(" / " + String.valueOf(formatter.format(Math.floor(totalTime.toSeconds()))));
});
// Slider Binding
timeSlider.sliderValueProperty().addListener((ov) -> {
if (timeSlider.isTheValueChanging()) {
if (null != player)
// multiply duration by percentage calculated by
// slider position
player.seek(totalTime.multiply(timeSlider
.sliderValueProperty().getValue() / 100.0));
else
timeSlider.sliderValueProperty().setValue(0);
}
});
//Applying Toggle Group to Buttons
playButton.setToggleGroup(group);
pauseButton.setToggleGroup(group);
// Action for Buttons
playButton.setOnAction(e -> {
play();
});
pauseButton.setOnAction(e -> {
pause();
});
//show the stage
primaryStage.setTitle("Media Player");
primaryStage.setScene(scene);
primaryStage.show();
}
public void play(){
player.play();
playButton.setSelected(true);
}
public void pause(){
player.pause();
playButton.setSelected(false);
}
private class SliderBar extends StackPane {
private Slider slider = new Slider();
private ProgressBar progressBar = new ProgressBar();
public SliderBar() {
getChildren().addAll(progressBar, slider);
bindValues();
}
private void bindValues(){
progressBar.prefWidthProperty().bind(slider.widthProperty());
progressBar.progressProperty().bind(slider.valueProperty().divide(100));
}
public DoubleProperty sliderValueProperty() {
return slider.valueProperty();
}
public boolean isTheValueChanging() {
return slider.isValueChanging();
}
}
public static void main(String[] args) {
launch(args);
}
}
A simple look while it plays
You can style the mediaplayer using stylesheet. You can go through JavaFX CSS Reference for advanced topic on css.
For a mediaplayer with advanced features like:
Adding songs to a Playlist
Playing songs one after another
Drag and drop songs into mediaview
and much more, you can go visit this example.