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.
Related
I'm working on a little game. So I create the game interface (countains the gun, the canvas which I use as gamespace and an interface for the user to control is gun). I place the different elements in the window and there is my problem. When I execute my code, all is well placed but once I use one of the buttons (buttons in both codes) or the slider (second code), the slider and the fire button replace themselves. And I don't understand why because I never asked this rellocation in my code. Also, when the items rellocate, I can't use any other items excepted the fire button and the slider.
Here are screenshots of what I have before using a button (first screenshot) (it's also how I want the interface to be) and the second screenshot shows the rellocation I have.
How it looks when I use nothing.
How it looks when I use a button or the slider.
Main.java :
package application;
import bureaux.Bureau;
import canons.Canon;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.control.ToolBar;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class Main extends Application{
private StackPane root, rootBureau;
private Scene scene;
private Stage stage;
private Text joueur;
private Button menu, musique, ajoutJoueur;
private FlowPane rootJeu;
private Bureau bureauJoueur;
private ToolBar toolBar;
private Canon canonJoueur;
#Override
public void start(Stage primaryStage) throws IOException {
getRoot();
getScene();
stage = primaryStage;
creerInterface();
stage.setTitle("Mad Java Guns");
stage.setResizable(false);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
public void creerInterface(String mode) { // creating the gamespace and the objects that the user need to play
getToolBar().getItems().addAll(getMusique(), getAjoutJoueur());
getRootBureau().getChildren().add(getBureauJoueur());
getRootJeu().getChildren().add(getCanonJoueur());
getRoot().getChildren().addAll(getToolBar(), getJoueur(), getRootBureau(), getRootJeu());
}
// Getters
public StackPane getRoot() {
if(root == null) {
root = new StackPane();
}
return root;
}
public Scene getScene() {
if(scene == null) {
scene = new Scene(root,1000,800);
}
return scene;
}
public Text getJoueur() { // gamespace
if(joueur == null) {
joueur = new Text("Espace de jeu");
joueur.setFont(Font.font("Arial", 20));
joueur.setTranslateY(120);
}
return joueur;
}
public ToolBar getToolBar() {
if(toolBar == null) {
toolBar = new ToolBar();
toolBar.setTranslateY(122);
toolBar.setTranslateX(3);
toolBar.setStyle("-fx-background-color: transparent");
}
return toolBar;
}
public Button getMusique() { // button too change the music in game
if (musique == null) {
musique = new Button("Musique");
musique.setOnMouseClicked(e -> {
System.out.println("musique"); // not coded yet
});
musique.setFocusTraversable(false);
}
return musique;
}
public Button getAjoutJoueur() { // add players in the game
if(ajoutJoueur == null) {
ajoutJoueur = new Button("Ajouter un joueur");
ajoutJoueur.setOnMouseClicked(e -> {
System.out.println("ajoutJoueur"); //not coded yet
});
ajoutJoueur.setFocusTraversable(false);
}
return ajoutJoueur;
}
public StackPane getRootBureau() { // pane where the user's interface will be placed
if(rootBureau == null) {
rootBureau = new StackPane();
rootBureau.setStyle("-fx-background-color: lightgrey");
rootBureau.setMaxSize(990, 250);
rootBureau.setTranslateY(270);
}
return rootBureau;
}
public Bureau getBureauJoueur() { // user's interface
if(bureauJoueur == null) {
bureauJoueur = new Bureau("Billy", getCanonJoueur());
}
return bureauJoueur;
}
}
Class Bureau.java :
package bureaux;
import canons.Canon;
import javafx.geometry.Orientation;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.Slider;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
public class Bureau extends Parent {
private Slider sliderCanon;
private HBox boxPrincipale;
private VBox boxControlesCanon;
private Button feu;
public Bureau(String nom, Canon canon) {
getBoxControlesCanon().getChildren().addAll(getSliderCanon(), getFeu());
getBoxPrincipale().getChildren().add(getBoxControlesCanon());
this.setTranslateX(-480); // placing the boxes
this.setTranslateY(-95);
this.getChildren().add(getBoxPrincipale());
}
//Getteurs
public HBox getBoxPrincipale() {
if(boxPrincipale == null) { // return a HBox which countains the VBox (next function)
// and other elements which aren't created yet.
boxPrincipale = new HBox();
}
return boxPrincipale;
}
public VBox getBoxControlesCanon() { // return a VBox which countains the controls of the gun
//(gun not showed in the code, doesn't concern the problem)
if(boxControlesCanon == null) {
boxControlesCanon = new VBox();
boxControlesCanon.setSpacing(20);
}
return boxControlesCanon;
}
public Slider getSliderCanon() { //slider to orient the gun (gun not showed in the code, doesn't concern the problem)
if(sliderCanon == null) {
sliderCanon = new Slider(0, 360, 0);
sliderCanon.setOrientation(Orientation.VERTICAL);
sliderCanon.valueProperty().addListener(e -> {
System.out.println(sliderCanon.getValue());
});
sliderCanon.setShowTickMarks(true);
sliderCanon.setShowTickLabels(true);
sliderCanon.setMajorTickUnit(90f);
}
return sliderCanon;
}
public Button getFeu() { // fire button
if(feu == null) {
feu = new Button("Feu");
feu.setOnMouseClicked(e -> {
System.out.println("Feu");
});
feu.setFocusTraversable(false);
}
return feu;
}
}
Please ask for more informations if necessary. Thanks for your help.
EDIT : sorry for the unpoliteness on top of this text, I used to edit it and add "Hello" but it just don't want to show it :/
You are using Bureau extends Parent. You will have to be more specific and used the nodes that will produce the outcome you need.
Try something like Bureau extends HBox. Then
getBoxControlesCanon().getChildren().add(new VBox(getSliderCanon(), getFeu()));
To get the left alignment, you may need to do something like
getBoxControlesCanon().getChildren().addAll(new VBox(getSliderCanon(), getFeu()), someOtherNode);
HBox.setHGrow(someOtherNode, Priority.ALWAYS);
If you look at Parent compared to VBox, you will see that Parent does not describe how children nodes will be laid out. A lot of nodes that are a subclass of Parent do describe how their children nodes will be laid out.
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.
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();
});
});
}
}
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.
Media player class is good. However, I can't play a mp3 file stored in another class (when mouse clicked). Could someone check my code?
package mediaplayer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.media.Media;
import javafx.stage.Stage;
public class MediaPlayer extends Application {
private static final String MEDIA_URL = "http://download.oracle.com/otndocs/products/javafx/oow2010-2.flv";
private static String arg1;
#Override public void start(Stage stage) {
stage.setTitle("Media Player");
Group root = new Group();
Scene scene = new Scene(root,600,265);
// 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);
MediaControl mediaControl = new MediaControl(mediaPlayer);
scene.setRoot(mediaControl);
scene.getStylesheets().add(MediaPlayer.class.getResource("mediaplayer.css").toExternalForm());
// show stage
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
if (args.length > 0) {
arg1 = args[0];
}
Application.launch(args);
}
}
This is the class I am trying to use to play my audio file:
package mediaplayer;
import java.awt.Cursor;
/**
*
* #author Yves
*/
public class LacherPrise extends javax.swing.JFrame {
/**
* Creates new form LacherPrise
*/
public LacherPrise() {
this.setVisible(true);
// définition de la taille de la fenêtre de l’éditeur
setBounds(200, 100, 800, 600);
initComponents();
}
When I run the program (on the mouseclicked below), I get these two errors:
Error no1: Exception in thread "AWT-EventQueue-0" java.lang.UnsupportedOperationException: Not yet implemented
Error no2:Exception in thread "Thread-3" java.lang.IllegalStateException: Toolkit not initialized
I would need help on how to implement Exception.
private void audio010MouseClicked(java.awt.event.MouseEvent evt) {
//getting URL to a sound file stored locally
String MEDIA_URL = "file:///C:/Users/Yves/Documents/NetBeansProjects/ExamenFinSessionJavaFX/src/RessourcesLacherPrise/Aff010.mp3";
Media media = new Media(MEDIA_URL.toString());
MediaPlayer MediaPlayer = new MediaPlayer();
MediaPlayer.play(MEDIA_URL);
}
The main problem i believe is that the JavaFX toolkit has not been initialized. Take a look at the following question:
JavaFX 2.1: Toolkit not initialized
Simply putting this at the start of your code could solve the problem:
new JFXPanel();