Sylwia Dorota Kedzia Sylwia is a developer at IDR Solutions working on JavaFX Development and on the NetBeans JavaFX Plugin. She is very passionate about programming and aims to improve constantly.

How to write a Media Player in JavaFX using NetBeans IDE – Part 2

2 min read

Media PlayerIn my previous article “How to write a Media Player in JavaFX using NetBeans IDE – Part 1 “ I showed you how to to create Media Player where in this post I am going to show you how to add all the functionality into it.

The start

To start we have to once again modify the start , therefore replace the start with the following lines of code. This modification will allow you to add all the functionality to the buttons and convert the Media player to the NetBeans plugin in the future.

 

 

MediaPlayer mediaPlayer;
private Label time;
Duration duration;
Button fullScreenButton;
Scene scene;
Media media;
double width;
double height;
MediaView mediaView;

@Override
public void start(Stage primaryStage) {

scene = setScene(this.width, this.height);

primaryStage.setTitle("Media Player!");
primaryStage.setScene(scene);

primaryStage.show();
}

Press Alt+Shift+F on your keyboard to format the code in NetBeans.

 

Add setScene() method

public Scene setScene(double width, double height) {
this.height = height;
this.width = width;
//Add your own path of the vidio that you want to play
String path = "F:/MediaPl/src/mediapl/Tom and Jerry Beach YouTube.mp4";

media = new Media(new File(path).toURI().toString());

mediaPlayer = new MediaPlayer(media);
//AutoPlay set to false
mediaPlayer.setAutoPlay(false);
mediaView = new MediaView(mediaPlayer);

// DropShadow effect
DropShadow dropshadow = new DropShadow();
dropshadow.setOffsetY(5.0);
dropshadow.setOffsetX(5.0);
dropshadow.setColor(Color.WHITE);

mediaView.setEffect(dropshadow);

BorderPane borderPane = new BorderPane();
borderPane.setCenter(mediaView);
borderPane.setBottom(addToolBar());

borderPane.setStyle("-fx-background-color: Black");
scene = new Scene(borderPane, 600, 600);
scene.setFill(Color.BLACK);
return scene;
}

 

Add functionality to the Buttons:

Buttons

Play  playButton

playButton.setOnAction((ActionEvent e) -> {
mediaPlayer.play();
});

Pause  pauseButton:

pauseButton.setOnAction((ActionEvent e) -> {
mediaPlayer.pause();
});

Forward  forwardButton:

forwardButton.setOnAction((ActionEvent e) -> {
mediaPlayer.seek(mediaPlayer.getCurrentTime().multiply(1.5));
});

Back  backButton:

backButton.setOnAction((ActionEvent e) -> {
mediaPlayer.seek(mediaPlayer.getCurrentTime().divide(1.5));
});

First  firstButton:

firstButton.setOnAction((ActionEvent e) -> {
mediaPlayer.seek(mediaPlayer.getStartTime());
mediaPlayer.stop();
});

Last  lastButton:

lastButton.setOnAction((ActionEvent e) -> {
mediaPlayer.seek(mediaPlayer.getTotalDuration());
mediaPlayer.stop();
});

Reload  reloadButton:

reloadButton.setOnAction((ActionEvent e) -> {
mediaPlayer.seek(mediaPlayer.getStartTime());
});

Minimize  fullscreenButton:

The action to this particular button has to be added to the start just before primaryStage.show(); line of code

fullScreenButton.setOnAction((ActionEvent e) -> {
if (primaryStage.isFullScreen()) {
primaryStage.setFullScreen(false);
} else {
primaryStage.setFullScreen(true);
}
});

Files  filesButton:

filesButton.setOnAction((ActionEvent e) -> {
FileChooser fc = new FileChooser();
fc.getExtensionFilters().add(new ExtensionFilter("*.flv", "*.mp4", "*.mpeg"));
File file = fc.showOpenDialog(null);
String path = file.getAbsolutePath();
path = path.replace("\\", "/");
media = new Media(new File(path).toURI().toString());
mediaPlayer.stop();
mediaPlayer = new MediaPlayer(media);
mediaPlayer.setAutoPlay(true);
mediaView.setMediaPlayer(mediaPlayer);
});

time Label:

time = new Label();
time.setTextFill(Color.YELLOW);
time.setPrefWidth(80);

mediaPlayer.currentTimeProperty().addListener((Observable ov) -> {
updateValues();
});

mediaPlayer.setOnReady(() -> {
duration = mediaPlayer.getMedia().getDuration();
updateValues();
});

 

Add updateValues() method

protected void updateValues() {
if (time != null) {
runLater(() -> {
Duration currentTime = mediaPlayer.getCurrentTime();
time.setText(formatTime(currentTime, duration));

});
}
}

 

Add formatTime() method

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

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

The updateValues and formatTime methods was taken from the Oracle tutorial: “3 Controlling Media Playback” which can be found here.

All done!

So that is all the code that allows you to create Media Player in JavaFx. You can also create a NetBeans plugin using this code. If your interested on how to do so please follow my previous articles:

How to write a WebBrowser plugin in JavaFX for the NetBeans IDE

Integrating PDF to HTML5 conversion into NetBeans platform – WebView and JavaFx clients.

I hope you found this guide useful, let us know what you think.

If you’re a first-time reader, or simply want to be notified when we post new articles and updates, you can keep up to date by social media (TwitterFacebook and Google+) or the Blog RSS.

IDRsolutions develop a Java PDF Viewer and SDK, an Adobe forms to HTML5 forms converter, a PDF to HTML5 converter and a Java ImageIO replacement. On the blog our team post anything interesting they learn about.

Sylwia Dorota Kedzia Sylwia is a developer at IDR Solutions working on JavaFX Development and on the NetBeans JavaFX Plugin. She is very passionate about programming and aims to improve constantly.

13 Replies to “How to write a Media Player in JavaFX using…”

  1. in to uri.tostring there should be a error of incompatible of file into string and there is no option of mediaview. i think u understand what can i write…..plz sugeest a solution

    1. Hi, It could be because you haven’t downloaded any media or the directory path isn’t pointing to the place where the media is being kept? Try checking these things and letting me know if the problem still persists. Thank you.

  2. package application;

    import java.io.File;
    import java.net.MalformedURLException;

    import javafx.application.Application;
    import javafx.beans.InvalidationListener;
    import javafx.beans.Observable;
    import javafx.event.ActionEvent;
    import javafx.geometry.Insets;
    import javafx.geometry.Pos;
    import javafx.stage.FileChooser;
    import javafx.stage.FileChooser.ExtensionFilter;
    import javafx.stage.Stage;
    import javafx.util.Duration;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.Label;
    import javafx.scene.control.Menu;
    import javafx.scene.control.MenuItem;
    import javafx.scene.control.Slider;
    import javafx.scene.effect.DropShadow;
    import javafx.scene.input.MouseEvent;
    import javafx.scene.layout.BorderPane;
    import javafx.scene.layout.HBox;
    import javafx.scene.media.Media;
    import javafx.scene.media.MediaException;
    import javafx.scene.media.MediaPlayer;
    import javafx.scene.media.MediaView;
    import javafx.scene.paint.Color;
    import javafx.application.Platform;

    public class Main extends Application {
    MediaPlayer mediaPlayer;
    private Label time;
    Duration duration;
    Button fullScreenButton;
    Scene scene;
    Media media;
    double width;
    double height;
    MediaView mediaView;
    private Label playTime;
    protected Slider vol;

    public void start(final Stage primaryStage) {
    scene = setScene(this.width, this.height);
    MenuItem open = new MenuItem(“open”);
    Menu file = new Menu(“File”);
    file.getItems().add(open);
    primaryStage.setTitle(“Media Player!”);
    primaryStage.setScene(scene);

    fullScreenButton.setOnAction((ActionEvent e) -> {
    if (primaryStage.isFullScreen()) {
    primaryStage.setFullScreen(false);
    } else {
    primaryStage.setFullScreen(true);
    }
    });
    primaryStage.show();
    }

    public Scene setScene(double width, double height) {
    this.height = height;
    String path = “D:/Lets Be Cops.mp4”;

    media = new Media(new File(path).toURI().toString());

    mediaPlayer = new MediaPlayer(media);

    mediaPlayer.setAutoPlay(false);
    mediaView = new MediaView(mediaPlayer);

    DropShadow dropshadow = new DropShadow();
    dropshadow.setOffsetY(5.0);
    dropshadow.setOffsetX(5.0);
    dropshadow.setColor(Color.WHITE);

    mediaView.setEffect(dropshadow);

    BorderPane borderPane = new BorderPane();
    borderPane.setCenter(mediaView);
    borderPane.setBottom(addToolBar());

    borderPane.setStyle(“-fx-background-color: Black”);
    scene = new Scene(borderPane, 600, 600);
    scene.setFill(Color.BLACK);
    return scene;
    }
    private HBox addToolBar() {
    HBox toolBar = new HBox();
    toolBar.setPadding(new Insets(20));
    toolBar.setAlignment(Pos.CENTER);
    toolBar.alignmentProperty().isBound();
    toolBar.setSpacing(5);
    toolBar.setStyle(“-fx-background-color: Black”);
    Button firstButton = new Button(“|<");
    Button backButton = new Button("<“);
    Button pauseButton = new Button(“||”);
    Button forwardButton = new Button(“>>”);
    Button lastButton = new Button(“>|”);
    Button reloadButton = new Button(“@”);
    Button filesButton = new Button(“|=|”);
    Button fullScreenButton = new Button(“[]”);
    Slider vol = new Slider();
    Slider time = new Slider();
    Label volume = new Label(“volume: “);
    toolBar.getChildren().addAll(filesButton, firstButton, backButton, playButton, pauseButton, forwardButton, lastButton, reloadButton, time, fullScreenButton, volume);
    playButton.setOnAction((ActionEvent e) -> {
    mediaPlayer.play();
    });
    playButton.addEventHandler(MouseEvent.MOUSE_ENTERED, (MouseEvent e) -> {
    playButton.setStyle(“-fx-background-color: Black”);
    playButton.setStyle(“-fx-body-color: Black”);
    });
    playButton.addEventHandler(MouseEvent.MOUSE_EXITED, (MouseEvent e) -> {
    playButton.setStyle(“-fx-background-color: Black”);
    });
    pauseButton.setOnAction((ActionEvent e) -> {
    mediaPlayer.pause();
    });
    pauseButton.addEventHandler(MouseEvent.MOUSE_ENTERED, (MouseEvent e) -> {
    pauseButton.setStyle(“-fx-background-color: Black”);
    pauseButton.setStyle(“-fx-body-color: Black”);
    });
    pauseButton.addEventHandler(MouseEvent.MOUSE_EXITED, (MouseEvent e) -> {
    pauseButton.setStyle(“-fx-background-color: Black”);
    });
    forwardButton.setOnAction((ActionEvent e) -> {
    mediaPlayer.seek(mediaPlayer.getCurrentTime().multiply(1.5));
    });
    forwardButton.addEventHandler(MouseEvent.MOUSE_ENTERED, (MouseEvent e) -> {
    forwardButton.setStyle(“-fx-background-color: Black”);
    forwardButton.setStyle(“-fx-body-color: Black”);
    });
    forwardButton.addEventHandler(MouseEvent.MOUSE_EXITED, (MouseEvent e) -> {
    forwardButton.setStyle(“-fx-background-color: Black”);
    });
    backButton.setOnAction((ActionEvent e) -> {
    mediaPlayer.seek(mediaPlayer.getCurrentTime().divide(1.5));
    });
    backButton.addEventHandler(MouseEvent.MOUSE_ENTERED, (MouseEvent e) -> {
    backButton.setStyle(“-fx-background-color: Black”);
    backButton.setStyle(“-fx-body-color: Black”);
    });
    backButton.addEventHandler(MouseEvent.MOUSE_EXITED, (MouseEvent e) -> {
    forwardButton.setStyle(“-fx-background-color: Black”);
    });
    firstButton.setOnAction((ActionEvent e) -> {
    mediaPlayer.seek(mediaPlayer.getStartTime());
    mediaPlayer.stop();
    });
    firstButton.addEventHandler(MouseEvent.MOUSE_ENTERED, (MouseEvent e) -> {
    firstButton.setStyle(“-fx-background-color: Black”);
    firstButton.setStyle(“-fx-body-color: Black”);
    });
    firstButton.addEventHandler(MouseEvent.MOUSE_EXITED, (MouseEvent e) -> {
    firstButton.setStyle(“-fx-background-color: Black”);
    });
    lastButton.setOnAction((ActionEvent e) -> {
    mediaPlayer.seek(mediaPlayer.getTotalDuration());
    mediaPlayer.stop();
    });
    lastButton.addEventHandler(MouseEvent.MOUSE_ENTERED, (MouseEvent e) -> {
    lastButton.setStyle(“-fx-background-color: Black”);
    lastButton.setStyle(“-fx-body-color: Black”);
    });
    lastButton.addEventHandler(MouseEvent.MOUSE_EXITED, (MouseEvent e) -> {
    lastButton.setStyle(“-fx-background-color: Black”);
    });
    reloadButton.setOnAction((ActionEvent e) -> {
    mediaPlayer.seek(mediaPlayer.getStartTime());
    });
    reloadButton.addEventHandler(MouseEvent.MOUSE_ENTERED, (MouseEvent e) -> {
    reloadButton.setStyle(“-fx-background-color: Black”);
    reloadButton.setStyle(“-fx-body-color: Black”);
    });
    reloadButton.addEventHandler(MouseEvent.MOUSE_EXITED, (MouseEvent e) -> {
    reloadButton.setStyle(“-fx-background-color: Black”);
    });
    filesButton.setOnAction((ActionEvent e) -> {
    FileChooser fc = new FileChooser();
    fc.getExtensionFilters().add(new ExtensionFilter(“*.flv”, “*.mp4”, “*.mpeg”,”*.avi”));
    File file = fc.showOpenDialog(null);
    String path = file.getAbsolutePath();
    path = path.replace(“\\”, “/”);
    media = new Media(new File(path).toURI().toString());
    mediaPlayer.stop();
    mediaPlayer = new MediaPlayer(media);
    mediaPlayer.setAutoPlay(true);
    mediaView.setMediaPlayer(mediaPlayer);
    });
    time.valueProperty().addListener(new InvalidationListener() {
    public void invalidated(Observable ov) {
    if (time.isValueChanging()) {
    // multiply duration by percentage calculated by slider position
    mediaPlayer.seek(duration.multiply(time.getValue() / 100.0));
    }
    }
    });
    vol.valueProperty().addListener(new InvalidationListener() {
    public void invalidated(Observable ov) {
    if (vol.isValueChanging()) {
    mediaPlayer.setVolume(vol.getValue() / 100.0);
    }
    }
    });

    return toolBar;

    }
    protected void updateValues() {
    if (playTime != null && time != null && vol != null) {
    Platform.runLater(new Runnable() {
    public void run() {
    Duration currentTime = mediaPlayer.getCurrentTime();
    playTime.setText(formatTime(currentTime, duration));
    time.setDisable(duration.isUnknown());
    if (!time.isDisabled()
    && duration.greaterThan(Duration.ZERO)) {

    }
    if (!vol.isValueChanging()) {
    vol.setValue((int)Math.round(mediaPlayer.getVolume()
    * 100));
    }
    }
    });
    }
    }
    private static String formatTime(Duration elapsed, Duration duration) {
    int intElapsed = (int)Math.floor(elapsed.toSeconds());
    int elapsedHours = intElapsed / (60 * 60);
    if (elapsedHours > 0) {
    intElapsed -= elapsedHours * 60 * 60;
    }
    int elapsedMinutes = intElapsed / 60;
    int elapsedSeconds = intElapsed – elapsedHours * 60 * 60
    – elapsedMinutes * 60;

    if (duration.greaterThan(Duration.ZERO)) {
    int intDuration = (int)Math.floor(duration.toSeconds());
    int durationHours = intDuration / (60 * 60);
    if (durationHours > 0) {
    intDuration -= durationHours * 60 * 60;
    }
    int durationMinutes = intDuration / 60;
    int durationSeconds = intDuration – durationHours * 60 * 60 –
    durationMinutes * 60;
    if (durationHours > 0) {
    return String.format(“%d:%02d:%02d/%d:%02d:%02d”,
    elapsedHours, elapsedMinutes, elapsedSeconds,
    durationHours, durationMinutes, durationSeconds);
    } else {
    return String.format(“%02d:%02d/%02d:%02d”,
    elapsedMinutes, elapsedSeconds,durationMinutes,
    durationSeconds);
    }
    } else {
    if (elapsedHours > 0) {
    return String.format(“%d:%02d:%02d”, elapsedHours,
    elapsedMinutes, elapsedSeconds);
    } else {
    return String.format(“%02d:%02d”,elapsedMinutes,
    elapsedSeconds);
    }
    }
    }
    public static void main(String[] args) {
    launch(args);
    }
    }

    Sir, this is my whole code. But it is not working. It keep on throwing Exception. Please correct my mistakes and let me know ASAP. Thank You.

  3. Thanks for this man, a real eye opener. Though it will be a milestone to completely transition from swing to JFX

  4. Great Job! Did you notice the bug in the oracle code for formatTime? It doesn’t work right if the movie is over an hour long.

    Bugs. Bugs. Bugs.

    Bugs. Bugs.Bugs.

    Wonderful Bugs. Wonderful Bugs! Yes I have gone stark raving mad.

  5. Here is a fix by the way……..

    private static String formatTime(Duration elapsed, Duration duration) {

    if (elapsed.greaterThan(Duration.ZERO) && duration.greaterThan(Duration.ZERO)) {
    long duration_ms = (long) Math.floor(duration.toMillis());
    long elapsed_ms = (long) Math.floor(elapsed.toMillis());

    return String.format(“%s%s of %s”,”Duration “, milliToHourFormat(elapsed_ms), milliToHourFormat(duration_ms));
    } else {
    return “”;
    }
    }

    private static String milliToHourFormat(long milliseconds) {
    int seconds = (int) (milliseconds / 1000) % 60;
    int minutes = (int) ((milliseconds / (1000 * 60)) % 60);
    int hours = (int) ((milliseconds / (1000 * 60 * 60)) % 24);
    StringBuffer sb = new StringBuffer();
    if (hours > 0) {
    sb.append(hours);
    sb.append(“:”);
    }
    if (minutes < 10) {
    sb.append("0");
    sb.append(minutes);
    sb.append(":");
    } else {
    sb.append(minutes);
    sb.append(":");
    }
    if (seconds < 10) {
    sb.append("0");
    sb.append(seconds);
    } else {
    sb.append(seconds);
    }
    return sb.toString();
    }

    Enjoy!

  6. The above comment should be sung to the tune of “Wonderful Spam” by Monty Python…

Leave a Reply

Your email address will not be published. Required fields are marked *