JavaFX

The JavaFX Media API

Photo of Andreas PomarolliAndreas PomarolliAugust 8th, 2016Last Updated: April 24th, 2019
1 2,244 29 minutes read

This is an article about the JavaFX Media API. JavaFX supports playing audio and video through the JavaFX Media API. HTTP live streaming of static media files and live feeds are also supported.

A number of media formats are supported, including AAC, AIFF, WAV, and MP3. FLV containing VP6 video and MP3 audio and MPEG-4 multimedia container with H.264/AVC video formats are also supported.

The support for a specific media format is platform dependent. Some media playback features and formats do not require any addition installations; some require third-party software to be installed.
 
 
 

 
The following table shows an overview of the whole article:

The following examples use Java SE 7 and JavaFX 2.2.

1. Introduction

The Media API consists of the following classes:

  • AudioClip
  • Media
  • MediaPlayer
  • MediaView
  • MediaErrorEvent
  • MediaException

AudioClip is used to play a short audio clip with minimal latency. Typically, this is useful for sound effects, which are usually short audio clips.

Use theMedia,MediaPlayer, andMediaView classes for playing audios and videos of longer length.

TheMedia andMediaPlayer classes are used to play audios as well as videos. An instance of theMedia class represents a media resource, which could be an audio or video. It provides the information about the media, for example, the duration of the media.

An instance of theMediaPlayer class provides controls for playing a media.

An instance of theMediaView class provides the view of a media being played by aMediaPlayer. AMediaView is used for viewing a video.

Several things can go wrong when you attempt to play a media, for example, the media format may not be supported or the media content may be corrupt.

An instance of theMediaException class represents a specific type of media error that may occur during media playback. When a media-related error occurs, aMediaErrorEvent is generated. You can handle the error by adding an appropriate event handler to the
media objects.

2. Playing Audio Clips

2.1 The Code

FxMediaExample1.java

import java.net.URL;import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.Label;import javafx.scene.control.Slider;import javafx.scene.layout.GridPane;import javafx.scene.layout.HBox;import javafx.scene.layout.VBox;import javafx.scene.media.AudioClip;import javafx.stage.Stage;public class FxMediaExample1 extends Application{private AudioClip audioClip;public static void main(String[] args) {Application.launch(args);}@Overridepublic void init() {// Create an AudioClip, which loads the audio data synchronouslyfinal URL resource = getClass().getResource("Test.mp3");audioClip = new AudioClip(resource.toExternalForm());}@Overridepublic void start(Stage stage) {// Create the ButtonsButton playButton = new Button("Play");Button stopButton = new Button("Stop");// Create the Slidersfinal Slider cycleSlider = new Slider(1, 5, 1);cycleSlider.setMajorTickUnit(1);cycleSlider.setShowTickLabels(true);final Slider volumeSlider = new Slider(0.0, 1.0, 0.5);volumeSlider.setMajorTickUnit(0.1);volumeSlider.setShowTickLabels(true);final Slider rateSlider = new Slider(0, 8, 4);rateSlider.setMajorTickUnit(1);rateSlider.setShowTickLabels(true);final Slider balanceSlider = new Slider(-1.0, 1.0, 0.0);balanceSlider.setMajorTickUnit(0.2);balanceSlider.setShowTickLabels(true);final Slider panSlider = new Slider(-1.0, 1.0, 0.0);panSlider.setMajorTickUnit(0.2);panSlider.setShowTickLabels(true);final Slider prioritySlider = new Slider(0.0, 10.0, 0.0);prioritySlider.setMajorTickUnit(1);prioritySlider.setShowTickLabels(true);// Create the Event Handlers for the ButtonplayButton.setOnAction(new EventHandler <ActionEvent>() {            public void handle(ActionEvent event)             {            audioClip.play();            }        });stopButton.setOnAction(new EventHandler <ActionEvent>() {            public void handle(ActionEvent event)             {            audioClip.stop();            }        });// Bind the PropertiesaudioClip.cycleCountProperty().bind(cycleSlider.valueProperty());audioClip.volumeProperty().bind(volumeSlider.valueProperty());audioClip.rateProperty().bind(rateSlider.valueProperty());audioClip.balanceProperty().bind(balanceSlider.valueProperty());audioClip.panProperty().bind(panSlider.valueProperty());audioClip.priorityProperty().bind(prioritySlider.valueProperty());// Create the GridPaneGridPane sliderPane = new GridPane();// Set horizontal and vertical SpacingsliderPane.setHgap(5);sliderPane.setVgap(10);// Add the details to the GridPanesliderPane.addRow(0, new Label("CycleCount:"), cycleSlider);sliderPane.addRow(1, new Label("Volume:"), volumeSlider);sliderPane.addRow(2, new Label("Rate:"), rateSlider);sliderPane.addRow(3, new Label("Balance:"), balanceSlider);sliderPane.addRow(4, new Label("Pan:"), panSlider);sliderPane.addRow(5, new Label("Priority:"), prioritySlider);// Create the HBoxHBox buttonBox = new HBox(5, playButton, stopButton);VBox root = new VBox(5,sliderPane, buttonBox);// Set the Sie of the VBoxroot.setPrefWidth(300);root.setPrefHeight(350);// Set the Style-properties of the HBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("An AucioClip Example");// Display the Stagestage.show();}}

An instance of theAudioClip class is used to play a short audio clip with minimal latency. Typically, this is useful for playing short audio clips, for example, a beep sound when the user makes an error or producing short sound effects in gaming applications.

TheAudioClip class provides only one constructor that takes a URL in string form, which is the URL of the audio source. The audio clip is immediately loaded into memory in raw, uncompressed form. This is the reason why you should not use this class for long-playing audio clips.

The source URL could use the HTTP, file, and JAR protocols. This means that you can play an audio clip from the Internet, the local file system, and a JAR file.

The following snippet of code creates anAudioClip:

// Create an AudioClip, which loads the audio data synchronouslyfinal URL resource = getClass().getResource("Test.mp3");audioClip = new AudioClip(resource.toExternalForm());

When anAudioClip object is created, the audio data are loaded into the memory and they are ready to be played immediately. Use theplay() method to play the audio and thestop() method to stop the playback:

/ Create the Event Handlers for the ButtonplayButton.setOnAction(new EventHandler <ActionEvent>() {    public void handle(ActionEvent event)     {audioClip.play();    }});stopButton.setOnAction(new EventHandler <ActionEvent>() {    public void handle(ActionEvent event)     {audioClip.stop();    }});

TheAudioClip class supports setting some audio properties when the clip is played:

  • cycleCount
  • volume
  • rate
  • balance
  • pan
  • priority

All of the above properties, except thecycleCount, can be set on theAudioClip class. Subsequent calls to theplay() method will use them as defaults. Theplay() method may also override the defaults for a specific playback. ThecycleCount property must be specified on theAudioClip and all subsequent playbacks will use the same value. ThecycleCount specifies the number of times the clip is played when theplay() method is called. It defaults to 1, which plays the clip only once.

Thevolume specifies the relative volume of the playback. The valid range is 0.0 to 1.0. A value of 0.0 represented muted, whereas 1.0 represents full volume.

Therate specifies the relative speed at which the audio is played. The valid range is 0.125 to 8.0. A value of 0.125 means the clip is played eight times slower, and the value of 8.0 means the clip will play eight times faster. Therate affects the playtime and the pitch. The default rate is 1.0, which plays the clip at the normalrate.

Thebalance specifies the relative volume for the left and right channels. The valid range is -1.0 to 1.0. A value of -1.0 sets the playback in the left channel at normal volume and mutes the right channel. A value of 1.0 sets the playback in the right channel at normal volume and mutes the left channel. The default value is 0.0, which sets the playback in both channels at normal volume.

Thepan specifies distribution of the clip between the left and right channels. The valid range is -1.0 to 1.0. A value of -1.0 shifts the clip entirely to the left channel. A value of 1.0 shifts the clip entirely to the right channel. The default value is 0.0, which plays the clip normally. Setting the value forpan for a mono clip has the same effect of setting the balance. You should change the default for this property only for audio clips using stereo sound.

Thepriority specifies the priority of the clip relative to other clips. It is used only when the number of playing clips exceeds the system limits. The playing clips with the lower priority will be stopped. It can be set to any integer. The default priority is set to zero.

Theplay() method is overloaded. It has three versions:

  • void play()
  • void play(double volume)
  • void play(double volume, double balance, double rate, double pan,int priority)

The no-args version of the method uses all of the properties set on theAudioClip. The other two versions can override the specified properties for a specific playback.

Suppose the volume for theAudioClip is set to 1.0. Callingplay() will play the clip at the volume 1.0 and callingplay(0.20) will play the clip at volume 0.20, leaving the volume property for theAudioClip unchanged at 1.0. That is, theplay() method
with parameters allows you to override theAudioClip properties on a per-playback basis.

TheAudioClip class contains anisPlaying() method to check if the clip is still playing. It returns true is the clip is playing. Otherwise, it returns false.

2.2 The GUI

A simple Audio Player Example:

A simple JavaFX AudioClip Example
A simple JavaFX AudioClip Example

3. Playing Media

3.1 The Code

FxMediaExample2.java

import java.net.URL;import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.effect.DropShadow;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.stage.Stage;public class FxMediaExample2 extends Application{public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage) {// Locate the media content in the CLASSPATHURL mediaUrl = getClass().getResource("Test.mp4");String mediaStringUrl = mediaUrl.toExternalForm();// Create a MediaMedia media = new Media(mediaStringUrl);// Create a Media Playerfinal MediaPlayer player = new MediaPlayer(media);// Automatically begin the playbackplayer.setAutoPlay(true);// Create a 400X300 MediaViewMediaView mediaView = new MediaView(player);mediaView.setFitWidth(400);mediaView.setFitHeight(300);mediaView.setSmooth(true);// Create the DropShadow effectDropShadow dropshadow = new DropShadow();dropshadow.setOffsetY(5.0);dropshadow.setOffsetX(5.0);dropshadow.setColor(Color.WHITE);mediaView.setEffect(dropshadow);// Create the ButtonsButton playButton = new Button("Play");Button stopButton = new Button("Stop");// Create the Event Handlers for the ButtonplayButton.setOnAction(new EventHandler <ActionEvent>() {            public void handle(ActionEvent event)             {            if (player.getStatus() == Status.PLAYING)             {            player.stop();            player.play();            }             else             {            player.play();            }            }        });stopButton.setOnAction(new EventHandler <ActionEvent>() {            public void handle(ActionEvent event)             {            player.stop();            }        });// Create the HBoxHBox controlBox = new HBox(5, playButton, stopButton);// Create the VBoxVBox root = new VBox(5,mediaView,controlBox);// Set the Style-properties of the HBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A simple Media Example");// Display the Stagestage.show();}}

JavaFX provides a unified API to work with audio and videos. You use the same classes to work with both. The Media API internally treats them as two different types of media that is transparent to the API users.

The Media API contains three core classes to play back media:

  • Media
  • MediaPlayer
  • MediaView

3.2 Creating a Media Object

An instance of theMedia class represents a media resource, which could be an audio or a video. It provides the information related to the media, for example, the duration, metadata, data, and so forth.

If the media is a video, it provides the width and height of the video. AMedia object is immutable. It is created by supplying a string which contains the path of the media resource, as in the following code:

// Locate the media content in the CLASSPATHURL mediaUrl = getClass().getResource("Test.mp4");String mediaStringUrl = mediaUrl.toExternalForm();// Create a MediaMedia media = new Media(mediaStringUrl);

TheMedia class contains the following properties, which are read-only:

  • duration
  • width
  • height
  • error
  • onError

Theduration specifies the duration of the media in seconds. It is aDuration object. If the duration is unknown, it isDuration.UNKNOWN.

Thewidth andheight give the width and height of the source media in pixels, respectively. If the media does not have width and height, they are set as zero.

Theerror andonError properties are related. Theerror property represents theMediaException that occurs during the loading of the media. TheonError is aRunnable object that you can set to get notified when an error occurs. Therun() method of theRunnable is called when an error occurs.

3.3 Creating a MediaPlayer Object

AMediaPlayer provides the controls, for example, play, pause, stop, seek, play speed, volume adjustment, for playing the media. TheMediaPlayer provides only one constructor that takes aMedia object as an argument:

// Create a Media Playerfinal MediaPlayer player = new MediaPlayer(media);

You can get the reference of the media from theMediaPlayer using thegetMedia() method of theMediaPlayer class.

Like theMedia class, theMediaPlayer class also containserror andonError properties to report errors. When an error occurs on theMediaPlayer, the same error is also reported on theMedia object.

3.4 Creating a MediaView Node

AMediaView is aNode. It provides the view of a media being played by aMediaPlayer. Note that an audio clip does not have visuals. If you try creating aMediaView for an audio content, it would be empty. To watch a video, you create aMediaView and add it to a Scene Graph.

TheMediaView class provides two constructors:

one no-args constructor and one that takes aMediaPlayer as an argument:

  • public MediaView()
  • public MediaView(MediaPlayer mediaPlayer)

The no-args constructor creates aMediaView that is attached to anyMediaPlayer. You will need to set aMediaPlayer using the setter for themediaPlayer property:

// Create a 400X300 MediaViewMediaView mediaView = new MediaView();mediaView.setMediaPlayer(player);mediaView.setFitWidth(400);mediaView.setFitHeight(300);

The other constructor lets you specify aMediaPlayer for theMediaView:

// Create a 400X300 MediaViewMediaView mediaView = new MediaView(player);mediaView.setFitWidth(400);mediaView.setFitHeight(300);

3.5 Customizing the MediaView

If the media has a view (e.g., a video), you can customize the size, area, and quality of the video using the following properties:

  • fitHeight
  • fitWidth
  • preserveRatio
  • smooth
  • viewport
  • x
  • y

ThefitWidth andfitHeight properties specify the resized width and height of the video, respectively. By default, they are zero, which means that the original width and height of the media will be used.

mediaView.setfitWidth(400);mediaView.setFitHeight(300);

ThepreserveRatio property specifies whether to preserve the aspect ratio of the media while resizing. By default, it is false.

Thesmooth property specifies the quality of the filtering algorithm to be used in resizing the video. The default value is platform dependent. If it is set to true, a better-quality filtering algorithm is used.

mediaView.setSmooth(true);

Aviewport is a rectangular region to view part of a graphic. Theviewport,x, andy properties together let you specify the rectangular area in the video that will be shown in theMediaView.

AMediaView is aNode. Therefore, to give a better visual experience to the audience, you can also apply effects and transformations to theMediaView.

3.6 Combining Media, MediaPlayer, and MediaView

The content of a media can be used simultaneously by multipleMedia objects. However, oneMedia object can be associated with only one media content in its lifetime.

AMedia object can be associated with multipleMediaPlayer objects. However, aMediaPlayer is associated with only oneMedia in its lifetime.

AMediaView may optionally be associated with aMediaPlayer. Of course, aMediaView that is not associated with aMediaPlayer does not have any visuals. TheMediaPlayer for aMediaView can be changed.

Changing theMediaPlayer for aMediaView is similar to changing the channel on a television. The view for theMediaView is provided by its currentMediaPlayer. You can associate the sameMediaPlayer with multiple MediaViews:

Different MediaViews may display different parts of the same media during the playback.

3.7 The GUI

The following image shows the GUI of theMediaPlayer:

A JavaFX MediaView Example
A JavaFX MediaView Example

4. Handling Playback Errors

4.1 The Code

FxMediaExample3.java

import java.net.URL;import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.TextArea;import javafx.scene.effect.DropShadow;import javafx.scene.layout.HBox;import javafx.scene.layout.VBox;import javafx.scene.media.Media;import javafx.scene.media.MediaErrorEvent;import javafx.scene.media.MediaException;import javafx.scene.media.MediaPlayer;import javafx.scene.media.MediaPlayer.Status;import javafx.scene.media.MediaView;import javafx.scene.paint.Color;import javafx.stage.Stage;public class FxMediaExample3 extends Application{// Create the Area for Loggingprivate TextArea messageArea = new TextArea();public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage) {// Locate the media content in the CLASSPATHURL mediaUrl = getClass().getResource("Test.mp4");String mediaStringUrl = mediaUrl.toExternalForm();// Create a Mediafinal Media media = new Media(mediaStringUrl);// Create a Media Playerfinal MediaPlayer player = new MediaPlayer(media);// Automatically begin the playbackplayer.setAutoPlay(true);// Create a 400X300 MediaViewfinal MediaView mediaView = new MediaView(player);mediaView.setFitWidth(400);mediaView.setFitHeight(300);mediaView.setSmooth(true);// Create the DropShadow effectDropShadow dropshadow = new DropShadow();dropshadow.setOffsetY(5.0);dropshadow.setOffsetX(5.0);dropshadow.setColor(Color.WHITE);mediaView.setEffect(dropshadow);// Create the ButtonsButton playButton = new Button("Play");Button stopButton = new Button("Stop");// Create the Event Handlers for the ButtonplayButton.setOnAction(new EventHandler <ActionEvent>() {            public void handle(ActionEvent event)             {            if (player.getStatus() == Status.PLAYING)             {            player.stop();            player.play();            }             else             {            player.play();            }            }        });stopButton.setOnAction(new EventHandler <ActionEvent>() {            public void handle(ActionEvent event)             {            player.stop();            }        });// Create Handlers for handling Errorsplayer.setOnError(new Runnable() {            public void run()             {                // Handle asynchronous error in Player object.            printMessage(player.getError());            }        });media.setOnError(new Runnable() {            public void run()             {                // Handle asynchronous error in Media object.            printMessage(media.getError());            }        });mediaView.setOnError(new EventHandler <MediaErrorEvent>(){public void handle(MediaErrorEvent event) {                // Handle asynchronous error in MediaView.            printMessage(event.getMediaError());            }});// Create the HBoxHBox controlBox = new HBox(5, playButton, stopButton);// Create the VBoxVBox root = new VBox(5,mediaView,controlBox,messageArea);// Set the Style-properties of the HBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("Handling Media Errors");// Display the Stagestage.show();}private void printMessage(MediaException error){MediaException.Type errorType = error.getType();String errorMessage = error.getMessage();messageArea.appendText("\n" + "Type:" + errorType + ", error mesage:" + errorMessage);}}

An instance of theMediaException class, which inherits from theRuntimeException class, represents a media error that may occur in aMedia,MediaPlayer, andMediaView.

Media playback may fail for a number of reasons. The API users should be able to identify specific errors. TheMediaException class defines a static enumMediaException.Type whose constants identify the type of error. TheMediaException class contains agetType() method that returns one of the constants of theMediaException.Type enum.

The constants in theMediaException.Type enum are listed below:

  • MEDIA_CORRUPTED
  • MEDIA_INACCESSIBLE
  • MEDIA_UNAVAILABLE
  • MEDIA_UNSPECIFIED
  • MEDIA_UNSUPPORTED
  • OPERATION_UNSUPPORTED
  • PLAYBACK_HALTED
  • PLAYBACK_ERROR
  • UNKNOWN

TheMEDIA_CORRUPTED error type indicates that the media is corrupted or invalid.

TheMEDIA_INACCESSIBLE error type indicates that the media is inaccessible. However, the media may exist.

TheMEDIA_UNAVAILABLE error type indicates that that media does not exist or it is unavailable.

TheMEDIA_UNSPECIFIED error type indicates that the media has not been specified.

TheMEDIA_UNSUPPORTED error type indicates that the media is not supported by the platform.

TheOPERATION_UNSUPPORTED error type indicates that the operation performed on the media is not supported by the platform.

ThePLAYBACK_HALTED error type indicates an unrecoverable error that has halted the playback.

ThePLAYBACK_ERROR error type indicates a playback error that does not fall into any other described categories.

TheUNKNOWN error type indicates that an unknown error has occurred.

TheMedia andMediaPlayer classes contain an error property that is aMediaException. All three classes contain anonError property, which is an event handler that is invoked when an error occurs. The types of the onError properties in these classes are not consistent.

It is aRunnable for theMedia andMediaPlayer classes and theMediaErrorEvent for theMediaView class.

The following snippet of code shows how to handle errors on aMedia,MediaPlayer, andMediaView.

// Create Handlers for handling Errorsplayer.setOnError(new Runnable() {    public void run()     {// Handle asynchronous error in Player object.printMessage(player.getError());    }});media.setOnError(new Runnable() {    public void run()     {// Handle asynchronous error in Media object.printMessage(media.getError());    }});mediaView.setOnError(new EventHandler <MediaErrorEvent>(){    public void handle(MediaErrorEvent event)     {// Handle asynchronous error in MediaView.printMessage(event.getMediaError());    }});

Media error handlers are invoked on the JavaFX Application Thread. Therefore, it is safe to update the Scene Graph from the handlers.

It is recommended that you enclose the creation of theMedia,MediaPlayer, andMediaView objects in a try-catch block and handle the exception appropriately. TheonError handlers for these objects are involved after the objects are created. If an error occurs during the creation of these objects, those handlers will not be available.

4.2 The GUI

The following GUI shows aMediaPlayer with Error Handling:

An JavaFX Media Example with Error Handling
An JavaFX Media Example with Error Handling

5. State Transitions of the MediaPlayer

5.1 The Code

FxMediaExample4.java

import java.net.URL;import javafx.application.Application;import javafx.beans.value.ChangeListener;import javafx.beans.value.ObservableValue;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.TextArea;import javafx.scene.effect.DropShadow;import javafx.scene.layout.HBox;import javafx.scene.layout.VBox;import javafx.scene.media.Media;import javafx.scene.media.MediaErrorEvent;import javafx.scene.media.MediaException;import javafx.scene.media.MediaPlayer;import javafx.scene.media.MediaPlayer.Status;import javafx.scene.media.MediaView;import javafx.scene.paint.Color;import javafx.stage.Stage;public class FxMediaExample4 extends Application{// Create the Area for Loggingprivate TextArea messageArea = new TextArea();public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage) {// Locate the media content in the CLASSPATHURL mediaUrl = getClass().getResource("Test.mp4");String mediaStringUrl = mediaUrl.toExternalForm();// Create a Mediafinal Media media = new Media(mediaStringUrl);// Create a Media Playerfinal MediaPlayer player = new MediaPlayer(media);// Automatically begin the playbackplayer.setAutoPlay(true);// Create a 400X300 MediaViewfinal MediaView mediaView = new MediaView(player);mediaView.setFitWidth(400);mediaView.setFitHeight(300);mediaView.setSmooth(true);// Create the DropShadow effectDropShadow dropshadow = new DropShadow();dropshadow.setOffsetY(5.0);dropshadow.setOffsetX(5.0);dropshadow.setColor(Color.WHITE);mediaView.setEffect(dropshadow);// Create the ButtonsButton playButton = new Button("Play");Button stopButton = new Button("Stop");// Create the Event Handlers for the ButtonplayButton.setOnAction(new EventHandler <ActionEvent>() {            public void handle(ActionEvent event)             {            if (player.getStatus() == Status.PLAYING)             {            player.stop();            player.play();            }             else             {            player.play();            }            }        });stopButton.setOnAction(new EventHandler <ActionEvent>() {            public void handle(ActionEvent event)             {            player.stop();            }        });// Create Handlers for handling Errorsplayer.setOnError(new Runnable() {            public void run()             {                // Handle asynchronous error in Player object.            printMessage(player.getError());            }        });media.setOnError(new Runnable() {            public void run()             {                // Handle asynchronous error in Media object.            printMessage(media.getError());            }        });mediaView.setOnError(new EventHandler <MediaErrorEvent>(){public void handle(MediaErrorEvent event) {                // Handle asynchronous error in MediaView.            printMessage(event.getMediaError());            }});// Add a ChangeListener to the playerplayer.statusProperty().addListener(new ChangeListener<MediaPlayer.Status>() {// Log the Message    public void changed(ObservableValue<? extends MediaPlayer.Status> ov,            final MediaPlayer.Status oldStatus, final MediaPlayer.Status newStatus)     {    messageArea.appendText("\nStatus changed from " + oldStatus + " to " + newStatus);    }});// Add a Handler for PLAYING statusplayer.setOnPlaying(new Runnable() {            public void run()             {            messageArea.appendText("\nPlaying now");            }});// Add a Handler for STOPPED statusplayer.setOnStopped(new Runnable() {            public void run()             {            messageArea.appendText("\nStopped now");            }});// Create the HBoxHBox controlBox = new HBox(5, playButton, stopButton);// Create the VBoxVBox root = new VBox(5,mediaView,controlBox,messageArea);// Set the Style-properties of the HBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A State Transition Example");// Display the Stagestage.show();}private void printMessage(MediaException error){MediaException.Type errorType = error.getType();String errorMessage = error.getMessage();messageArea.appendText("\n" + "Type:" + errorType + ", error mesage:" + errorMessage);}}

AMediaPlayer always has a status. The current status of aMediaPlayer is indicated by the read-onlystatus property. The status changes when an action is performed on theMediaPlayer. It cannot be set directly. The status of aMediaPlayer is defined by one of the eight constants in theMediaPlayer.Status enum:

  • UNKNOWN
  • READY
  • PLAYING
  • PAUSED
  • STALLED
  • STOPPED
  • HALTED
  • DISPOSE

TheMediaPlayer transitions from one status to another when one of the following methods is called:

  • play()
  • pause()
  • stop()
  • dispose()

When aMediaPlayer is created, its status isUNKNOWN. Once the media is prerolled and it is ready to be played, theMediaPlayer transitions fromUNKNOWN toREADY. Once theMediaPlayer exits theUNKNOWN status, it cannot reenter it in its lifetime.

TheMediaPlayer transitions to thePLAYING status when theplay() method is called. This status indicates that the media is playing. Note if theautoPlay property is set to true, theMediaPlayer may enter thePLAYING status without calling theplay() method explicitly after it is created.

When theMediaPlayer is playing, it may enter theSTALLED status if it does not have enough data in its buffer to play. This status indicates that theMediaPlayer is buffering data. When enough data are buffered, it goes back to thePLAYING status.

When aMediaPlayer is stalled, calling thepause() andstop() methods, it transitions to thePAUSED andSTOPPED status, respectively. In that case, the buffering continues. However, theMediaPlayer does not transition to thePLAYING status once enough data are buffered. Rather, it stays in thePAUSED orSTOPPED status.

Calling thepaused() method transitions theMediaPlayer to thePAUSED status. Calling thestop() method transitions theMediaPlayer to theSTOPPED status.

In cases of an unrecoverable error, theMediaPlayer transitions to theHALTED terminal status. This status indicates that theMediaPlayer cannot be used again. You must create a newMediaPlayer if you want to play the media again.

Thedispose() method frees all of the resources associated with theMediaPlayer. However, theMedia object used by the
MediaPlayer can still be used. Calling thedispose() method transitions theMediaPlayer to the terminal statusDISPOSED.

It is common to display the status of theMediaPlayer in an application. Add aChangeListener to thestatus property to listen for any status changes.

Typically, you will be interested in receiving a notification when the status of theMediaPlayer changes. There are two ways to get the notifications:

  • By adding a ChangeListener to the status property
  • By setting status change handlers

The first method is suitable if you are interested in listening for any type of status change. The following snippet of code shows this method:

// Add a ChangeListener to the playerplayer.statusProperty().addListener(new ChangeListener<MediaPlayer.Status>() {// Log the Message    public void changed(ObservableValue<? extends MediaPlayer.Status> ov,    final MediaPlayer.Status oldStatus, final MediaPlayer.Status newStatus)     {messageArea.appendText("\nStatus changed from " + oldStatus + " to " + newStatus);    }});

The second method is suitable if you are interested in handling a specific type of status change. TheMediaPlayer class contains the following properties that can be set toRunnable objects:

  • onReady
  • onPlaying
  • onRepeat
  • onStalled
  • onPaused
  • onStopped
  • onHalted

Therun() method of theRunnable object is called when theMediaPlayer enters into the specific status.

For example, therun() method of theonPlaying handler is called when the player enters thePLAYING status.

Want to master JavaFX ?
Subscribe to our newsletter and download theJavaFXProgramming Cookbookright now!
In order to get you prepared for your JavaFX development needs, we have compiled numerous recipes to help you kick-start your projects. Besides reading them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

The following snippet of code shows how to set handlers for a specific type of status change:

// Add a Handler for PLAYING statusplayer.setOnPlaying(new Runnable() {public void run() {messageArea.appendText("\nPlaying now");}});// Add a Handler for STOPPED statusplayer.setOnStopped(new Runnable() {public void run() {messageArea.appendText("\nStopped now");}});

5.2 The GUI

The following GUI shows aMediaPlayer with State Transitions:

An JavaFX Media Example with State Transitions
An JavaFX Media Example with State Transitions

6. Controlling Media Properties

6.1 The Code

FxMediaExample5.java

import java.net.URL;import javafx.application.Application;import javafx.beans.InvalidationListener;import javafx.beans.Observable;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.Label;import javafx.scene.control.Slider;import javafx.scene.control.TextArea;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.stage.Stage;public class FxMediaExample5 extends Application{// Create the Area for Loggingprivate TextArea messageArea = new TextArea();public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage) {// Create the Slidersfinal Slider cycleSlider = new Slider(1, 5, 1);cycleSlider.setMajorTickUnit(1);cycleSlider.setShowTickLabels(true);final Slider volumeSlider = new Slider(0.0, 1.0, 0.5);volumeSlider.setMajorTickUnit(0.1);volumeSlider.setShowTickLabels(true);final Slider rateSlider = new Slider(0, 8, 4);rateSlider.setMajorTickUnit(1);rateSlider.setShowTickLabels(true);final Slider balanceSlider = new Slider(-1.0, 1.0, 0.0);balanceSlider.setMajorTickUnit(0.2);balanceSlider.setShowTickLabels(true);// Locate the media content in the CLASSPATHURL mediaUrl = getClass().getResource("Test.mp4");String mediaStringUrl = mediaUrl.toExternalForm();// Create a Mediafinal Media media = new Media(mediaStringUrl);// Create a Media Playerfinal MediaPlayer player = new MediaPlayer(media);// Automatically begin the playbackplayer.setAutoPlay(true);// Create a 400X300 MediaViewfinal MediaView mediaView = new MediaView(player);mediaView.setFitWidth(400);mediaView.setFitHeight(300);mediaView.setSmooth(true);// Create the DropShadow effectDropShadow dropshadow = new DropShadow();dropshadow.setOffsetY(5.0);dropshadow.setOffsetX(5.0);dropshadow.setColor(Color.WHITE);mediaView.setEffect(dropshadow);// Create the ButtonsButton playButton = new Button("Play");Button stopButton = new Button("Stop");// Create the Event Handlers for the ButtonplayButton.setOnAction(new EventHandler <ActionEvent>() {            public void handle(ActionEvent event)             {            if (player.getStatus() == Status.PLAYING)             {            player.stop();            player.play();            }             else             {            player.play();            }            }        });stopButton.setOnAction(new EventHandler <ActionEvent>() {            public void handle(ActionEvent event)             {            player.stop();            }        });// Create the Listener for the SliderscycleSlider.valueProperty().addListener(new InvalidationListener(){@Overridepublic void invalidated(Observable ov) {if (cycleSlider.isValueChanging()) {messageArea.appendText("\nCycle Count changed to: " + (int)cycleSlider.getValue());player.setCycleCount((int)cycleSlider.getValue());}}});volumeSlider.valueProperty().addListener(new InvalidationListener(){@Overridepublic void invalidated(Observable ov) {if (volumeSlider.isValueChanging()) {messageArea.appendText("\nVolume changed to: " + volumeSlider.getValue());player.setVolume(volumeSlider.getValue());}}});rateSlider.valueProperty().addListener(new InvalidationListener(){@Overridepublic void invalidated(Observable ov) {if (rateSlider.isValueChanging()) {messageArea.appendText("\nRate changed to: " + rateSlider.getValue());player.setRate(rateSlider.getValue());}}});balanceSlider.valueProperty().addListener(new InvalidationListener(){@Overridepublic void invalidated(Observable ov) {if (balanceSlider.isValueChanging()) {messageArea.appendText("\nBalance changed to: " + balanceSlider.getValue());player.setVolume(balanceSlider.getValue());}}});// Add Handlers for End and Repeatplayer.setOnEndOfMedia(new Runnable(){            public void run()             {            messageArea.appendText("\nEnd of media !");            }});player.setOnRepeat(new Runnable(){            public void run()             {            messageArea.appendText("\nRepeating media !");            }});// Create the GridPaneGridPane sliderPane = new GridPane();// Set horizontal and vertical SpacingsliderPane.setHgap(5);sliderPane.setVgap(10);// Add the details to the GridPanesliderPane.addRow(0, new Label("CycleCount:"), cycleSlider);sliderPane.addRow(1, new Label("Volume:"), volumeSlider);sliderPane.addRow(2, new Label("Rate:"), rateSlider);sliderPane.addRow(3, new Label("Balance:"), balanceSlider);// Create the HBoxHBox controlBox = new HBox(5, playButton, stopButton);// Create the VBoxVBox root = new VBox(5,mediaView,controlBox,sliderPane,messageArea);// Set the Style-properties of the HBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A Media Properties Example");// Display the Stagestage.show();}}

6.2 Repeating Media Playback

A media can be played repeatedly for a specified number of times or even indefinitely. ThecycleCount property specifies the number of times a playback will be repeated. By default, it is set to 1. Set it toMediaPlayer.INDEFINITE to repeat the playback indefinitely until the player is paused or stopped. The readonlycurrentCount property is set to the number of completed playback cycles. It is set to 0 when the media is playing the first cycle. At the end of the first cycle, it is set to 1; it is incremented to 2 at the end of second cycle, and so on.

The following code would set a playback cycle of four times:

// The playback should repeat 4 timesplayer.setCycleCount(4);

You can receive a notification when the end of media for a cycle in playback is reached. Set aRunnable for theonEndOfMedia property of theMediaPlayer class to get the notification. Note that if a playback continues for four cycles, the end of media notification will be sent four times.

// Add Handlers for End and Repeatplayer.setOnEndOfMedia(new Runnable(){public void run() {messageArea.appendText("\nEnd of media !");}});

You can add anonRepeat event handler that is called when the end of media for a playback cycle is reached and the playback is going to repeat. It is called after theonEndOfMedia event handler:

player.setOnRepeat(new Runnable(){public void run() {messageArea.appendText("\nRepeating media !");}});

6.3 Controlling the Playback Rate

Therate property of theMediaPlayer specifies the rate of the playback. The valid range is 0.0 to 8.0. For example, a rate of 2.0 plays the media two times faster than the normal rate. The default value is 1.0, which plays the media at the normal rate. The read-onlycurrentRate property is the current rate of playback.

The following code would set the rate at three times the normal rate:

player.setRate(3.0);

6.4 Controlling the Playback Volume

Three properties in theMediaPlayer class control the volume of the audio in the media:

  • volume
  • mute
  • balance

Thevolume specifies the volume of the audio. The range is 0.0 to 1.0. A value of 0.0 makes the audio inaudible, whereas a value of 1.0 plays it at full volume. The default value is 1.0.

Themute specifies whether the audio is produced by theMediaPlayer. By default, its value is false and the audio is produced. Setting it to true does not produce audio. Note that setting the mute property does not affect the volume property.

Suppose the volume is set to 1.0 and the muted is set to true. There is no audio
being produced. When the mute is set to false, the audio will use the volume property that is 1.0 and it will play at full volume. The following code would set the volume at half:

player.setVolumne(0.5);player.setMute(true)

Thebalance specifies the relative volume for the left and right channels. The valid range is -1.0 to 1.0. A value of -1.0 sets the playback in the left channel at normal volume and mutes the right channel. A value of 1.0 sets the playback in the right channel at normal volume and mutes the left channel. The default value is 0.0, which sets the playback in both channels at normal volume.

6.5 The GUI

The following GUI shows aMediaPlayer with Properties:

An JavaFX Media Example with Properties
An JavaFX Media Example with Properties

7. Tracking Media Time

7.1 The Code

FxMediaExample6.java

import java.net.URL;import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.effect.DropShadow;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.stage.Stage;import javafx.util.Duration;public class FxMediaExample6 extends Application{public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage) {// Locate the media content in the CLASSPATHURL mediaUrl = getClass().getResource("Test.mp4");String mediaStringUrl = mediaUrl.toExternalForm();// Create a Mediafinal Media media = new Media(mediaStringUrl);// Create a Media Playerfinal MediaPlayer player = new MediaPlayer(media);// Automatically begin the playbackplayer.setAutoPlay(true);// Set the Times of the Playerplayer.setStartTime(Duration.minutes(1));player.setStopTime(Duration.minutes(2));// Create a 400X300 MediaViewfinal MediaView mediaView = new MediaView(player);mediaView.setFitWidth(400);mediaView.setFitHeight(300);mediaView.setSmooth(true);// Create the DropShadow effectDropShadow dropshadow = new DropShadow();dropshadow.setOffsetY(5.0);dropshadow.setOffsetX(5.0);dropshadow.setColor(Color.WHITE);mediaView.setEffect(dropshadow);// Create the ButtonsButton playButton = new Button("Play");Button stopButton = new Button("Stop");// Create the Event Handlers for the ButtonplayButton.setOnAction(new EventHandler <ActionEvent>() {            public void handle(ActionEvent event)             {            if (player.getStatus() == Status.PLAYING)             {            player.stop();            player.play();            }             else             {            player.play();            }            }        });stopButton.setOnAction(new EventHandler <ActionEvent>() {            public void handle(ActionEvent event)             {            player.stop();            }        });// Create the HBoxHBox controlBox = new HBox(5, playButton, stopButton);// Create the VBoxVBox root = new VBox(5,mediaView,controlBox);// Set the Style-properties of the HBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A Tracking Media Example");// Display the Stagestage.show();}}

Displaying the media duration and the elapsed time for a playback are important feedback for the audience. A good understanding of these duration types is important in developing a good media playback dashboard.

Different types ofDuration can be associated with a media:

  • The current duration of a media playing media
  • The duration of the media playback
  • The duration of the media play for one cycle
  • The start offset time
  • The end offset time
  • onStopped
  • onHalted
  • DISPOSE

By default, a media plays for its original duration. For example, if the duration of the media is 30 minutes, the media will play for 30 minutes in one cycle. TheMediaPlayer lets you specify the length of the playback, which can be anywhere in theDuration of the media. For example, for each playback cycle, you can specify that only the middle 10 minutes (11th to 12th) of the media should be played. The length of the media playback is specified by the following two properties of theMediaPlayer class:

  • startTime
  • stopTime

Both properties are of theDuration type. ThestartTime andstopTime are the time offsets where the media should start and stop playing for each cycle, respectively. By default, the startTime is set toDuration.ZERO and thestopTime is set to the duration of the media.

The following snippet of code sets these properties, so the media will be played from the first minute to the second minute:

// Set the Times of the Playerplayer.setStartTime(Duration.minutes(1));player.setStopTime(Duration.minutes(2));

7.2 The GUI

The following GUI shows aMediaPlayer with Time Tracking:

An JavaFX Media Example with Media Time Tracking
An JavaFX Media Example with Media Time Tracking

8. Marking Positions in the Media

8.1 The Code

FxMediaExample7.java

import java.net.URL;import javafx.application.Application;import javafx.collections.ObservableMap;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.TextArea;import javafx.scene.effect.DropShadow;import javafx.scene.layout.HBox;import javafx.scene.layout.VBox;import javafx.scene.media.Media;import javafx.scene.media.MediaMarkerEvent;import javafx.scene.media.MediaPlayer;import javafx.scene.media.MediaPlayer.Status;import javafx.scene.media.MediaView;import javafx.scene.paint.Color;import javafx.stage.Stage;import javafx.util.Duration;import javafx.util.Pair;public class FxMediaExample7 extends Application{// Create the Area for Loggingprivate TextArea messageArea = new TextArea();public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage) {// Locate the media content in the CLASSPATHURL mediaUrl = getClass().getResource("Test.mp4");String mediaStringUrl = mediaUrl.toExternalForm();// Create a Mediafinal Media media = new Media(mediaStringUrl);// Create the MarkersObservableMap<String, Duration> markers = media.getMarkers();markers.put("START", Duration.ZERO);markers.put("INTERVAL", media.getDuration().divide(2.0));markers.put("END", media.getDuration());// Create a Media Playerfinal MediaPlayer player = new MediaPlayer(media);// Automatically begin the playbackplayer.setAutoPlay(true);// Create a 400X300 MediaViewfinal MediaView mediaView = new MediaView(player);mediaView.setFitWidth(400);mediaView.setFitHeight(300);mediaView.setSmooth(true);// Create the DropShadow effectDropShadow dropshadow = new DropShadow();dropshadow.setOffsetY(5.0);dropshadow.setOffsetX(5.0);dropshadow.setColor(Color.WHITE);// Set the Effect on the MediaViewmediaView.setEffect(dropshadow);// Create the ButtonsButton playButton = new Button("Play");Button stopButton = new Button("Stop");// Create the Event Handlers for the ButtonplayButton.setOnAction(new EventHandler <ActionEvent>() {            public void handle(ActionEvent event)             {            if (player.getStatus() == Status.PLAYING)             {            player.stop();            player.play();            }             else             {            player.play();            }            }        });stopButton.setOnAction(new EventHandler <ActionEvent>() {            public void handle(ActionEvent event)             {            player.stop();            }        });// Add a marker event handlerplayer.setOnMarker(new EventHandler <MediaMarkerEvent>() {            public void handle(MediaMarkerEvent event)             {    Pair<String, Duration> marker = event.getMarker();    String markerText = marker.getKey();    Duration markerTime = marker.getValue();    messageArea.appendText("\nReached the marker " + markerText + " at " + markerTime);            }});// Create the HBoxHBox controlBox = new HBox(5, playButton, stopButton);// Create the VBoxVBox root = new VBox(5,mediaView,controlBox,messageArea);// Set the Style-properties of the HBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A Markers Example");// Display the Stagestage.show();}}

You can associate markers with specific point on the media timeline. Markers are simply text that are useful in a number of ways. You can use them to insert advertisements.

For example, you can insert a URL as the marker text. When the marker is reached, you can pause playing the media and play another media. Note that playing another media involves creating newMedia andMediaPlayer objects. You can reuse aMediaView. When you are playing the advertisement video, associate theMediaView with the newMediaPlayer. When the advertisement playback is finished, associate the MediaView back to the mainMediaPlayer.

TheMedia class contains agetMarkers() method that returns anObservableMap. You need to add the (key, value) pairs in the map to add markers.

The following snippet of code adds three markers to a media:

// Create the MarkersObservableMap<String, Duration> markers = media.getMarkers();markers.put("START", Duration.ZERO);markers.put("INTERVAL", media.getDuration().divide(2.0));markers.put("END", media.getDuration());

TheMediaPlayer fires aMediaMarkerEvent when a marker is reached. You can register a handler for this event in theonMarker property of theMediaPlayer.

The following snippet of code shows how to handle theMediaMarkerEvent. ThegetMarker() method of the event returns a Pair whose key and value are the marker text and marker duration, respectively.

// Add a marker event handlerplayer.setOnMarker(new EventHandler <MediaMarkerEvent>() {public void handle(MediaMarkerEvent event) {Pair<String, Duration> marker = event.getMarker();String markerText = marker.getKey();Duration markerTime = marker.getValue();messageArea.appendText("\nReached the marker " + markerText + " at " + markerTime);}});

8.2 The GUI

The following GUI shows aMediaPlayer with Markers:

An JavaFX Media Example with Position Markers
An JavaFX Media Example with Position Markers

9. Showing Media Metadata

9.1 The Code

FxMediaExample8.java

import java.net.URL;import javafx.application.Application;import javafx.collections.ObservableMap;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.TextArea;import javafx.scene.effect.DropShadow;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.stage.Stage;public class FxMediaExample8 extends Application{// Create the Area for Loggingprivate TextArea messageArea = new TextArea();public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage) {// Locate the media content in the CLASSPATHURL mediaUrl = getClass().getResource("Test.mp3");String mediaStringUrl = mediaUrl.toExternalForm();// Create a Mediafinal Media media = new Media(mediaStringUrl);// Create a Media Playerfinal MediaPlayer player = new MediaPlayer(media);// Automatically begin the playbackplayer.setAutoPlay(false);// Create a 400X300 MediaViewfinal MediaView mediaView = new MediaView(player);mediaView.setFitWidth(400);mediaView.setFitHeight(300);mediaView.setSmooth(true);// Create the DropShadow effectDropShadow dropshadow = new DropShadow();dropshadow.setOffsetY(5.0);dropshadow.setOffsetX(5.0);dropshadow.setColor(Color.WHITE);mediaView.setEffect(dropshadow);// Create the ButtonsButton playButton = new Button("Play");Button stopButton = new Button("Stop");// Create the Event Handlers for the ButtonplayButton.setOnAction(new EventHandler <ActionEvent>() {            public void handle(ActionEvent event)             {            if (player.getStatus() == Status.PLAYING)             {            player.stop();            player.play();            }             else             {            player.play();            }            }        });stopButton.setOnAction(new EventHandler <ActionEvent>() {            public void handle(ActionEvent event)             {            player.stop();            }        });// Display the metadata data on the consoleplayer.setOnReady(new Runnable(){            public void run()             {        ObservableMap<String, Object> metadata = media.getMetadata();        for(String key : metadata.keySet())         {        messageArea.appendText("\n" + key + " = "  + metadata.get(key));        }            }});// Create the HBoxHBox controlBox = new HBox(5, playButton, stopButton);// Create the VBoxVBox root = new VBox(5,mediaView,controlBox,messageArea);// Set the Style-properties of the HBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A Metadata Example");// Display the Stagestage.show();}}

Some metadata may be embedded into a media that describe the media. Typically, the metadata contains the title, artist name, album name, genre, year, and so forth.

The following snippet of code displays the metadata for the media when theMediaPlayer enters theREADY status. Do not try reading the metadata just after creating theMedia object, as the metadata may not be available.

// Display the metadata data on the consoleplayer.setOnReady(new Runnable(){public void run() {ObservableMap<String, Object> metadata = media.getMetadata();for(String key : metadata.keySet()) {messageArea.appendText("\n" + key + " = "  + metadata.get(key));}}});

You cannot be sure whether there are metadata in a media or the type of metadata a media may contain. In your application, you can just look for the title, artist, album, and year. Alternatively, you could read all of the metadata and display them in a two-column table. Sometimes the metadata may contain an embedded image of the artist. You would need to check the class name of the value in the map to use the
image.

9.2 The GUI

The following GUI shows aMediaPlayer with Metadata:

An JavaFX Media Example with Metadata
An JavaFX Media Example with Metadata

10. Download Java Source Code

This was an example ofjavafx.scene.media

Download
You can download the full source code of this example here:JavaFxMediaExample.zip
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Andreas PomarolliAndreas PomarolliAugust 8th, 2016Last Updated: April 24th, 2019
1 2,244 29 minutes read
Photo of Andreas Pomarolli

Andreas Pomarolli

Andreas has graduated from Computer Science and Bioinformatics at the University of Linz. During his studies he has been involved with a large number of research projects ranging from software engineering to data engineering and at least web engineering. His scientific focus includes the areas of software engineering, data engineering, web engineering and project management. He currently works as a software engineer in the IT sector where he is mainly involved with projects based on Java, Databases and Web Technologies.

Related Articles

The JavaFX Print API

July 8th, 2016

JavaFX WebView Example

October 13th, 2016

JavaFX Canvas Example

May 18th, 2016

JavaFX CSS Tutorial

May 5th, 2016

JavaFX 2D Shape Example

October 21st, 2016
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.