Playing Video - Java JavaFX

Java examples for JavaFX:Video

Introduction

JavaFX media player supported formats are as follows:

  • AIFF
  • FXM, FLV
  • HLS
  • MP3
  • MP4
  • WAV

Demo Code


import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Point2D;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Slider;
import javafx.scene.input.DataFormat;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.media.Media;
import javafx.scene.media.MediaErrorEvent;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.WindowEvent;
import javafx.util.Duration;

public class Main extends Application {

  private MediaPlayer mediaPlayer;
  private MediaView mediaView;
  private Point2D anchorPt;
  private Point2D previousLocation;
  private Slider progressSlider;
  private ChangeListener<Duration> progressListener;
  private boolean paused = false;

  public static void main(String[] args) {
    Application.launch(args);//from  w  w  w .  j  av a  2s  . c om
  }

  @Override
  public void start(final Stage primaryStage) {
    primaryStage.setTitle("Playing Video");
    primaryStage.centerOnScreen();
    primaryStage.initStyle(StageStyle.TRANSPARENT);

    final Group root = new Group();
    final Scene scene = new Scene(root, 540, 300, Color.rgb(0, 0, 0, 0));

    Node applicationArea = createBackground(scene);
    root.getChildren().add(applicationArea);

    attachMouseEvents(scene, primaryStage);

    progressSlider = createSlider(scene);
    root.getChildren().add(progressSlider);

    scene.setOnDragOver((DragEvent event) -> {
      Dragboard db = event.getDragboard();
      if (db.hasFiles() || db.hasUrl() || db.hasString()) {
        event.acceptTransferModes(TransferMode.COPY);
        if (mediaPlayer != null) {
          mediaPlayer.stop();
        }
      } else {
        event.consume();
      }
    });
    progressListener = (ObservableValue<? extends Duration> observable,
        Duration oldValue, Duration newValue) -> {
      progressSlider.setValue(newValue.toSeconds());
    };
    scene
        .setOnDragDropped((DragEvent event) -> {
          Dragboard db = event.getDragboard();
          boolean success = false;
          URI resourceUrlOrFile = null;
          if (db.hasContent(DataFormat.URL)) {
            try {
              resourceUrlOrFile = new URI(db.getUrl());
            } catch (URISyntaxException ex) {
              ex.printStackTrace();
            }
          } else if (db.hasFiles()) {
            // dragged from the file system
            String filePath = null;
            for (File file : db.getFiles()) {
              filePath = file.getAbsolutePath();
            }
            resourceUrlOrFile = new File(filePath).toURI();
            success = true;
          }
          Media media = new Media(resourceUrlOrFile.toString());
          if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.currentTimeProperty().removeListener(progressListener);
            mediaPlayer.setOnPaused(null);
            mediaPlayer.setOnPlaying(null);
            mediaPlayer.setOnReady(null);
          }
          mediaPlayer = new MediaPlayer(media);
          mediaPlayer.currentTimeProperty().addListener(progressListener);
          mediaPlayer.setOnReady(() -> {
            progressSlider.setValue(1);
            progressSlider.setMax(mediaPlayer.getMedia().getDuration()
                .toMillis() / 1000);
            mediaPlayer.play();
          });
          if (mediaView == null) {
            mediaView = new MediaView();
            mediaView.setMediaPlayer(mediaPlayer);
            mediaView.setX(4);
            mediaView.setY(4);
            mediaView.setPreserveRatio(true);
            mediaView.setOpacity(.85);
            mediaView.setSmooth(true);

            mediaView.fitWidthProperty().bind(
                scene.widthProperty().subtract(220));
            mediaView.fitHeightProperty().bind(
                scene.heightProperty().subtract(30));
            root.getChildren().add(1, mediaView);
          }
          mediaView.setOnError((MediaErrorEvent event1) -> {
            event1.getMediaError().printStackTrace();
          });

          mediaView.setMediaPlayer(mediaPlayer);

          event.setDropCompleted(success);
          event.consume();
        });
    Group buttonArea = createButtonArea(scene);
    Node stopButton = new Button("Stop");
    Node playButton = new Button("Play");
    Node pauseButton = new Button("Pause");
    stopButton.setOnMousePressed((MouseEvent me) -> {
      if (mediaPlayer != null) {
        buttonArea.getChildren().removeAll(pauseButton, playButton);
        buttonArea.getChildren().add(playButton);
        mediaPlayer.stop();
      }
    });
    pauseButton.setOnMousePressed((MouseEvent me) -> {
      if (mediaPlayer != null) {
        buttonArea.getChildren().removeAll(pauseButton, playButton);
        buttonArea.getChildren().add(playButton);
        mediaPlayer.pause();
        paused = true;
      }
    });
    playButton.setOnMousePressed((MouseEvent me) -> {
      if (mediaPlayer != null) {
        buttonArea.getChildren().removeAll(pauseButton, playButton);
        buttonArea.getChildren().add(pauseButton);
        paused = false;
        mediaPlayer.play();
      }
    });
    buttonArea.getChildren().add(stopButton);
    buttonArea.getChildren().add(pauseButton);
    root.getChildren().add(buttonArea);
    Node closeButton = createCloseButton(scene);
    root.getChildren().add(closeButton);

    primaryStage.setOnShown((WindowEvent we) -> {
      previousLocation = new Point2D(primaryStage.getX(), primaryStage.getY());
    });

    primaryStage.setScene(scene);
    primaryStage.show();

  }

  private Group createButtonArea(final Scene scene) {
    Group buttonGroup = new Group();
    Rectangle buttonArea = new Rectangle();
    buttonArea.setArcWidth(15);
    buttonArea.setArcHeight(20);
    buttonArea.setFill(new Color(0, 0, 0, .55));
    buttonArea.setX(0);
    buttonArea.setY(0);
    buttonArea.setWidth(60);
    buttonArea.setHeight(30);
    buttonArea.setStroke(Color.rgb(255, 255, 255, .70));

    buttonGroup.getChildren().add(buttonArea);
    buttonGroup.translateXProperty().bind(
        scene.widthProperty().subtract(buttonArea.getWidth() + 6));
    buttonGroup.translateYProperty().bind(
        scene.heightProperty().subtract(buttonArea.getHeight() + 6));
    return buttonGroup;
  }

  private Node createBackground(Scene scene) {
    Rectangle applicationArea = new Rectangle();
    applicationArea.setArcWidth(20);
    applicationArea.setArcHeight(20);
    applicationArea.setFill(Color.rgb(0, 0, 0, .80));
    applicationArea.setX(0);
    applicationArea.setY(0);
    applicationArea.setStrokeWidth(2);
    applicationArea.setStroke(Color.rgb(255, 255, 255, .70));

    applicationArea.widthProperty().bind(scene.widthProperty());
    applicationArea.heightProperty().bind(scene.heightProperty());
    return applicationArea;
  }

  private Slider createSlider(Scene scene) {
    Slider slider = new Slider();
    slider.setMin(0);
    slider.setMax(100);
    slider.setValue(1);
    slider.setShowTickLabels(true);
    slider.setShowTickMarks(true);

    slider.valueProperty().addListener(
        (ObservableValue<? extends Number> observable, Number oldValue,
            Number newValue) -> {
          if (slider.isPressed()) {
            long dur = newValue.intValue() * 1000;
            mediaPlayer.seek(new Duration(dur));
          }
        });

    slider.translateYProperty().bind(scene.heightProperty().subtract(30));
    return slider;
  }

  private void attachMouseEvents(Scene scene, final Stage primaryStage) {
    scene.setOnMouseClicked((MouseEvent event) -> {
      if (event.getClickCount() == 2) {
        primaryStage.setFullScreen(!primaryStage.isFullScreen());
      }
    });
    scene.setOnMousePressed((MouseEvent event) -> {
      if (!primaryStage.isFullScreen()) {
        anchorPt = new Point2D(event.getScreenX(), event.getScreenY());
      }
    });
    scene.setOnMouseDragged((MouseEvent event) -> {
      if (anchorPt != null && previousLocation != null
          && !primaryStage.isFullScreen()) {
        primaryStage.setX(previousLocation.getX() + event.getScreenX()
            - anchorPt.getX());
        primaryStage.setY(previousLocation.getY() + event.getScreenY()
            - anchorPt.getY());
      }
    });
    scene
        .setOnMouseReleased((MouseEvent event) -> {
          if (!primaryStage.isFullScreen()) {
            previousLocation = new Point2D(primaryStage.getX(), primaryStage
                .getY());
          }
        });
  }

  private Node createCloseButton(Scene scene) {
    final Group closeApp = new Group();
    Circle closeButton = new Circle();
    closeButton.setCenterX(5);
    closeButton.setCenterY(0);
    closeButton.setRadius(7);
    closeButton.setFill(Color.rgb(255, 255, 255, .80));

    Text closeXmark = new Text(2, 4, "X");
    closeApp.translateXProperty().bind(scene.widthProperty().subtract(15));
    closeApp.setTranslateY(10);
    closeApp.getChildren().addAll(closeButton, closeXmark);
    closeApp.setOnMouseClicked((MouseEvent event) -> {
      Platform.exit();
    });
    return closeApp;
  }

}

Related Tutorials