JavaFX - Oracle Help Center

JavaFX - Oracle Help Center
Incorporating Media Assets Into JavaFX Applications
Release 2.2
April 2013
JavaFX Incorporating Media Assets Into JavaFX Applications, Release 2.2
Copyright © 2011, 2013 Oracle and/or its affiliates. All rights reserved.
Primary Author: Cindy Castillo
Contributing Author:
This software and related documentation are provided under a license agreement containing restrictions on
use and disclosure and are protected by intellectual property laws. Except as expressly permitted in your
license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license,
transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse
engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is
The information contained herein is subject to change without notice and is not warranted to be error-free. If
you find any errors, please report them to us in writing.
If this is software or related documentation that is delivered to the U.S. Government or anyone licensing it
on behalf of the U.S. Government, the following notice is applicable:
U.S. GOVERNMENT RIGHTS Programs, software, databases, and related documentation and technical data
delivered to U.S. Government customers are “commercial computer software” or “commercial technical
data” pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental
regulations. As such, the use, duplication, disclosure, modification, and adaptation shall be subject to the
restrictions and license terms set forth in the applicable Government contract, and, to the extent applicable
by the terms of the Government contract, the additional rights set forth in FAR 52.227-19, Commercial
Computer Software License (December 2007). Oracle America, Inc., 500 Oracle Parkway, Redwood City, CA
This software or hardware is developed for general use in a variety of information management
applications. It is not developed or intended for use in any inherently dangerous applications, including
applications that may create a risk of personal injury. If you use this software or hardware in dangerous
applications, then you shall be responsible to take all appropriate fail-safe, backup, redundancy, and other
measures to ensure its safe use. Oracle Corporation and its affiliates disclaim any liability for any damages
caused by use of this software or hardware in dangerous applications.
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of
their respective owners.
Intel and Intel Xeon are trademarks or registered trademarks of Intel Corporation. All SPARC trademarks
are used under license and are trademarks or registered trademarks of SPARC International, Inc. AMD,
Opteron, the AMD logo, and the AMD Opteron logo are trademarks or registered trademarks of Advanced
Micro Devices. UNIX is a registered trademark licensed through X/Open Company, Ltd.
This software or hardware and documentation may provide access to or information on content, products,
and services from third parties. Oracle Corporation and its affiliates are not responsible for and expressly
disclaim all warranties of any kind with respect to third-party content, products, and services. Oracle
Corporation and its affiliates will not be responsible for any loss, costs, or damages incurred due to your
access to or use of third-party content, products, or services.
1 Introduction to JavaFX Media
Supported Media Codecs........................................................................................................................ 1-1
HTTP Live Streaming Support .............................................................................................................. 1-2
Creating a Media Player.......................................................................................................................... 1-2
2 Embedding Media Into a Web Page
To Get Started............................................................................................................................................ 2-1
Create the Application............................................................................................................................. 2-2
3 Controlling Media Playback
Creating Controls .....................................................................................................................................
Add the Functional Logic Code .............................................................................................................
Modify the
Compile and Run the EmbeddedMedia ..............................................................................................
Part I
Part I
About This Tutorial
This tutorial describes the JavaFX media functionality available through the Java APIs
for JavaFX, including the formats of media files that are currently supported.
The document contains the following chapters:
Introduction to JavaFX Media
Embedding Media Into a Web Page
Controlling Media Playback
Introduction to JavaFX Media
The active growth of media content on the web has made video and audio an essential
part of rich Internet applications. The idea of broadening the horizons of traditional
media usage led to the creation of the JavaFX media functionality that is available
through a set of Java APIs. The package enables developers to
create media applications that provide media playback in the desktop window or
within a web page on supported platforms.
Figure 1–1 demonstrates a variety of possible media usages in JavaFX applications.
Figure 1–1 Samples of Media Usages
The operating systems and Java Runtime Environments (JREs) supported by JavaFX
media features are the same as those listed in the JavaFX SDK System Requirements
document. Refer to the JavaFX Release Documentation page for the appropriate
system requirements information for the version of JavaFX SDK you are using.
Supported Media Codecs
The formats currently supported are the following:
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
Introduction to JavaFX Media
HTTP Live Streaming Support
You may not integrate the On2 VP6 video decoder in the
design of a semiconductor or register transfer level (RTL) or any other
similar level necessary for development of semiconductor
implementation of the On2 VP6 video decoder.
The FLV container is supported by the media stack on the platforms supported by the
JavaFX SDK. A single movie encoded in this format works seamlessly on supported
platforms. Standard FLV MIME settings are required on the server side to enable
media streaming.
The MPEG-4 multimedia container is also supported on all operating systems
supported by the JavaFX SDK. On the Mac OS X and Windows 7 platforms, playback
will be functional without requiring additional software. However, the Linux
operating system and versions of Windows older than Windows 7 require the
installation of readily available third party software packages, as documented in the
JavaFX System Requirements. AAC and H.264/AVC decoding have certain
platform-dependent limitations, as described in the JavaFX Release Notes.
Decoding of some audio and video compression types relies on operating
system-specific media engines. The JavaFX media framework does not attempt to
handle all multimedia container formats and media encodings supported by these
native engines. Instead, the framework attempts to provide equivalent and well-tested
functionality across all platforms on which JavaFX is supported.
Some of the features supported by the JavaFX media stack include the following:
FLV container with MP3 and VP6
MP3 audio
MPEG-4 container with either AAC, H.264, or both
HTTP, FILE protocol support
Progressive download
Buffer progress
Playback functions (Play, Pause, Stop, Volume, Mute, Balance, Equalizer)
HTTP Live Streaming Support
With the addition of HTTP live streaming support, you can now download the playlist
file and playback video or audio segments using JavaFX Media. Media players are
now able to switch to alternate streams, as specified in the playlist file and based on
network conditions. For a given stream, there is a playlist file and a set of segments
into which the stream is broken. The stream can be either an MP3 raw stream or an
MPEG-TS containing multiplexed AAC audio and H.264 video. The stream can be
played on demand when the stream is a static file or played live when the stream is
actually a live feed. In both cases, the stream can adjust its bit rate and for video, its
resolution can be adjusted.
Creating a Media Player
The JavaFX media concept is based on the following entities.
1-2 Oracle JavaFX Incorporating Media Assets Into JavaFX Applications
Creating a Media Player
Media – A media resource, containing information about the media, such as its
source, resolution, and metadata
MediaPlayer – The key component providing the controls for playing media
MediaView – A Node object to support animation, translucency, and effects
Each element of the media functionality is available through the JavaFX API.
Figure 1–2 shows the classes that reside in the package. These
classes are interdependent and are used in combination to create an embedded media
Figure 1–2 Classes in the Package
The MediaPlayer class provides all the attributes and functions needed to control
media playback. You can either set the AUTO_PLAY mode, call the play() function
directly, or explicitly specify the number of times that the media should play. The
VOLUME variable and the BALANCE variable can be used to adjust the volume level and
left-right settings, respectively. The volume level range is from 0 to 1.0 (the maximum
value). The balance range is continuous from -1.0 on the far left, 0 at the center, and 1.0
at the right.
The play(), stop(), and pause() functions control media playback. Additionally, a
bundle of functions handles specific events when the player does one of the following:
Buffers data
Reaches the end of media
Stalls because it has not received data fast enough to continue playing
Encounters any of the errors defined in the MediaErrorEvent class
The MediaView class extends the Node class and provides a view of the media being
played by the media player. It is responsible mostly for effects and transformations. Its
mediaPlayer instance variable specifies the MediaPlayer object by which the
media is being played. Other Boolean attributes serve to apply the particular effect
provided by the Node class, for example, to enable the media player to be rotated.
Introduction to JavaFX Media
Creating a Media Player
For more information about the package, see the API
1-4 Oracle JavaFX Incorporating Media Assets Into JavaFX Applications
Embedding Media Into a Web Page
In this section, you’ll explore how to add animated media content to your web page by
creating a simple media panel. To create a media player you need to implement the
structure of the three nested objects that is shown in Figure 2–1.
Figure 2–1 Structure of the Embedded Media Player
To Get Started
You can build a JavaFX application using any development tool designed for creating
a Java application. The tool used in this document is the NetBeans IDE. Do the
following steps before continuing to build this document’s sample application that
uses the JavaFX Media features:
Use the JavaFX Release Documentation page to find the System
Requirements document that you need to verify that your system meets the
minimum requirements, including the version of NetBeans IDE.
Use the Installation Guide on the JavaFX Release Documentation page to
get the information on how to install the version of JavaFX SDK software you plan
to use.
Install the required NetBeans IDE using the NetBeans information provided in the
JavaFX System Requirements documents available from the JavaFX Release
Documentation page.
If necessary, get acquainted with the following documents to get familiar with
What Is JavaFX
Getting Started with JavaFX
JavaFX Architecture and Framework
Embedding Media Into a Web Page 2-1
Create the Application
Create the Application
From the NetBeans IDE, set up your JavaFX project as follows:
From the File menu, choose New Project.
In the JavaFX application category, choose JavaFX Application. Click Next.
Name the project EmbeddedMediaPlayer and ensure the Create
Application Class field has the value of
embeddedmediaplayer.EmbeddedMediaPlayer. Click Finish.
Copy the import statements in Example 2–1 and paste them in the file, replacing all of the import statements that
were automatically generated by the NetBeans IDE.
Example 2–1 Replace Default Import Statements
For now, ignore the warnings on the margin since the lines of code that use the
Media classes will be added in the next few steps.
Specify the media file source to be used and the String variable by adding the lines
in bold in Example 2–2. For this example, use the animated video located at or specify your own file. Add the lines after the public
class EmbeddedMediaPlayer line.
Example 2–2 Specify the Media File Source
public class EmbeddedMediaPlayer extends Application {
private static final String MEDIA_URL =
Modify the start method so that it looks like Example 2–3. This is will create an
empty scene with a group root node and dimension of 540 wide by 210 height.
Example 2–3 Modify the start Method
public void start(Stage primaryStage) {
primaryStage.setTitle("Embedded Media Player");
Group root = new Group();
Scene scene = new Scene(root, 540, 210);
Now, define the Media and the MediaPlayer objects by adding the code in
Example 2–4 before the primaryStage.setScene(scene) line. Set the
autoPlay variable to true so that the video can start immediately.
2-2 Oracle JavaFX Incorporating Media Assets Into JavaFX Applications
Create the Application
Example 2–4 Add media and mediaPlayer Objects
// create media player
Media media = new Media(MEDIA_URL);
MediaPlayer mediaPlayer = new MediaPlayer(media);
Define the MediaView object and add the media player to the Node-based viewer
by copying the comment and two lines of code in Example 2–5 and pasting it right
after the mediaPlayer.setAutoPlay(true) line.
Example 2–5 Define MediaView Object
// create mediaView and add media player to the viewer
MediaView mediaView = new MediaView(mediaPlayer);
Right-click on any whitespace and select Format to fix the line formatting after
adding the lines of code.
Right-click the EmbeddedMediaPlayer project node in the Projects pane and select
Clean and Build.
After a successful build, run your application by right-clicking the project node
and selecting Run.
If you are using the media file source used in this tutorial and
you are running the application behind a firewall, you might need to
set the application’s proxy in order for the application to be able to
access the media source file. Right-click the EmbeddedMediaPlayer
project node in the Project window, select Properties, and in the
Project Properties dialog, select Run. Set the VM Options field with
something similar to
-Dhttp.proxyPort=somePort#, where is your
company’s proxy server and somePort# is a port number you are
assigned to use.
10. Deploy the sample application you just built to a browser by embedding it into
your HTML content using the instructions in the Deployment in the
Browser document. Copy the code from the EmbeddedMediaPlayer.html file that
was automatically generated by the IDE to the target web page.
Embedding Media Into a Web Page 2-3
Create the Application
2-4 Oracle JavaFX Incorporating Media Assets Into JavaFX Applications
Controlling Media Playback
In this section you create a full-functional media player with graphical UI elements
that control the playback.
To create a media player you need to implement the structure of the three nested
media objects, encode graphical controls, and add some logic for playback functions,
as illustrated in the Figure 3–1 below.
Figure 3–1 Structure of Media Player with Playback Controls
You step through adding playback controls to the media player that you created in
Chapter 2, "Embedding Media Into a Web Page". If you haven’t already done so,
complete that media player application before proceeding with the rest of this chapter.
The media control panel you add consists of three elements: playButton, progress, and
Creating Controls
In this section you create a new JavaFX source file,, that will
contain the pane and UI controls for the play/pause, progress, and volume features.
With the EmbeddedMediaPlayer opened as the main project in the NetBeans IDE,
create a new JavaFX file to add to the project.
Use Ctrl+N or select File > New File from the IDE’s main menu.
Select Category JavaFX and file type JavaFX Main class. Click Next.
Controlling Media Playback
Creating Controls
In the Name and Location dialog, type MediaControl in the Class Name
In the Package field, select embeddedmediaplayer from the drop-down list
and click Finish.
Delete all the lines after package embeddedmediaplayer line.
Add the import statements that are shown in Example 3–1 to the top of the file.
Example 3–1 Import Statements to Add
Copy and paste the lines of code in Example 3–2 to create the BorderPane that will
hold the controls.
Example 3–2 Add MediaControl Class Code
public class MediaControl extends BorderPane {
MediaPlayer mp;
MediaView mediaView;
final boolean repeat = false;
boolean stopRequested = false;
boolean atEndOfMedia = false;
Duration duration;
Slider timeSlider;
Label playTime;
Slider volumeSlider;
HBox mediaBar;
public MediaControl(final MediaPlayer mp) { = mp;
setStyle("-fx-background-color: #bfc2c7;");
mediaView = new MediaView(mp);
Pane mvPane = new Pane() {
mvPane.setStyle("-fx-background-color: black;");
Copy the lines of code in Example 3–3 and paste them immediately after the line
that says setCenter(mvPane). This code adds the Media toolbar and the Play
Example 3–3 Add Media Toolbar and Play Button
mediaBar = new HBox();
mediaBar.setPadding(new Insets(5, 10, 5, 10));
3-2 Oracle JavaFX Incorporating Media Assets Into JavaFX Applications
Creating Controls
BorderPane.setAlignment(mediaBar, Pos.CENTER);
final Button playButton = new Button(">");
Add the import statements shown in Example 3–4 to the top of the list of import
Example 3–4 Add More Import Statements
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
Add the remainder of the UI controls to the control pane. Put the lines of code in
Example 3–5 after the mediaBar.getChildren().add(playButton); line and
before the setBottom(mediaBar) line.
Example 3–5 Add the Rest of the UI Controls
// Add spacer
Label spacer = new Label("
// Add Time label
Label timeLabel = new Label("Time: ");
// Add time slider
timeSlider = new Slider();
// Add Play label
playTime = new Label();
// Add the volume label
Label volumeLabel = new Label("Vol: ");
// Add Volume slider
volumeSlider = new Slider();
Add more import statements shown in Example 3–6 to the top of the file.
Controlling Media Playback
Add the Functional Logic Code
Example 3–6 Add More Import Statements
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
Add the Functional Logic Code
After all the controls have been created and added to the control panel, add the
functional logic to manage the media playback and make your application interactive.
Add the event handler and listener for the Play button. Copy and paste the lines of
code in Example 3–7 after the final Button playButton = new
Button(">") line and before the
mediaBar.getChildren().add(playButton) line.
Example 3–7 Add Play Button’s Event Handler and Listener
playButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
Status status = mp.getStatus();
if (status == Status.UNKNOWN || status == Status.HALTED)
// don't do anything in these states
if ( status == Status.PAUSED
|| status == Status.READY
|| status == Status.STOPPED)
// rewind the movie if we're sitting at the end
if (atEndOfMedia) {;
atEndOfMedia = false;
} else {
The import statements used by the code you just added from Example 3–7 could
have been added beforehand to avoid getting errors. But this time, to eliminate all
of marked errors, press Ctrl+Shift+I or right-click anywhere and select Fix
Imports. From the Fix All Imports dialog, select javafx.event.ActionEvent,, and
javafx.event.EventHandler from the drop-down menus. Click OK.
Add the following lines of code immediately after the lines of code you added
from Example 3–7 and before the line that says
mediaBar.getChildren().add(playButton). This code will handle the
Example 3–8 Add Listener Code
mp.currentTimeProperty().addListener(new InvalidationListener()
public void invalidated(Observable ov) {
3-4 Oracle JavaFX Incorporating Media Assets Into JavaFX Applications
Add the Functional Logic Code
mp.setOnPlaying(new Runnable() {
public void run() {
if (stopRequested) {
stopRequested = false;
} else {
mp.setOnPaused(new Runnable() {
public void run() {
mp.setOnReady(new Runnable() {
public void run() {
duration = mp.getMedia().getDuration();
mp.setCycleCount(repeat ? MediaPlayer.INDEFINITE : 1);
mp.setOnEndOfMedia(new Runnable() {
public void run() {
if (!repeat) {
stopRequested = true;
atEndOfMedia = true;
Note that the errors that appear will be fixed by adding more code in the next
Add listener for the time slider by adding the following code snippet after the line
that says timeSlider.setMaxWidth(Double.MAX_VALUE) and before the
line that says mediaBar.getChildren().add(timeSlider).
Example 3–9 Add Listener for Time Slider
timeSlider.valueProperty().addListener(new InvalidationListener() {
public void invalidated(Observable ov) {
if (timeSlider.isValueChanging()) {
// multiply duration by percentage calculated by slider position / 100.0));
5. Add listener for the volume slider control by adding the following code snippet
after the line that says volumeSlider.setMinWidth(30) and before the
Controlling Media Playback
Add the Functional Logic Code
Example 3–10
Add Listener for the Volume Control
volumeSlider.valueProperty().addListener(new InvalidationListener() {
public void invalidated(Observable ov) {
if (volumeSlider.isValueChanging()) {
mp.setVolume(volumeSlider.getValue() / 100.0);
6. Create Method updateValues used by the playback controls. Add it after the
public MediaControl() method.
Example 3–11
Add UpdateValues Method
protected void updateValues() {
if (playTime != null && timeSlider != null && volumeSlider != null) {
Platform.runLater(new Runnable() {
public void run() {
Duration currentTime = mp.getCurrentTime();
playTime.setText(formatTime(currentTime, duration));
if (!timeSlider.isDisabled()
&& duration.greaterThan(Duration.ZERO)
&& !timeSlider.isValueChanging()) {
* 100.0);
if (!volumeSlider.isValueChanging()) {
* 100));
7. Add the private method formatTime() that calculates the elapsed time the
media has been playing and formats it to be displayed on the control toolbar.
Example 3–12
Add Method for Calculating Elapsed Time
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",
3-6 Oracle JavaFX Incorporating Media Assets Into JavaFX Applications
Compile and Run the EmbeddedMedia
elapsedHours, elapsedMinutes, elapsedSeconds,
durationHours, durationMinutes, durationSeconds);
} else {
return String.format("%02d:%02d/%02d:%02d",
elapsedMinutes, elapsedSeconds,durationMinutes,
} else {
if (elapsedHours > 0) {
return String.format("%d:%02d:%02d", elapsedHours,
elapsedMinutes, elapsedSeconds);
} else {
return String.format("%02d:%02d",elapsedMinutes,
Lastly, fix the imports. Right-click in any white space and select
javafx.application.Platform and javafx.beans.Observable from the
Fix All Imports dialog. Click OK.
Modify the
To add the control, modify the file that you created in the
previous chapter and add the code to add the MediaControl object.
Copy the lines of code in Example 3–13 and paste them right after the
mediaPlayer.setAutoPlay(true) line.
Example 3–13
Add the Source Code to Create MediaControl Object
MediaControl mediaControl = new MediaControl(mediaPlayer);
Delete the three lines shown in Example 3–14, which previously created the
mediaView and mediaPlayer objects.
Example 3–14
Delete Lines of Code
// create mediaView and add media player to the viewer
MediaView mediaView = new MediaView(mediaPlayer);
Adjust the size of the scene’s height to accommodate the addition of the media
Example 3–15
Change the Scene’s Height
Scene scene = new Scene(root, 540, 241);
Compile and Run the EmbeddedMedia
Now build the application you just created in the previous section and run it.
Right-click the EmbeddedMediaPlayer project node and select Clean and Build.
If there are no build errors, right-click the node again and select Run. The media
player with control appears, similar to Figure 3–2 and begins to play.
Controlling Media Playback
Compile and Run the EmbeddedMedia
Figure 3–2 Media Player with Playback Controls
Stop and resume the video using the play/pause control button. Move forwards or
backwards through the video using the progress bar. Adjust the volume using the
volume control button.
Find the complete application code in the file.
3-8 Oracle JavaFX Incorporating Media Assets Into JavaFX Applications
Was this manual useful for you? yes no
Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Download PDF