Java Reference
In-Depth Information
content: [mediaView]
}
}
mediaPlayer.play();
}
As we can see in Listing 9-1, a Media object is created with a URI pointing to the media file. The Media
object is then used to create a MediaPlayer object. MediaPlayer is a class that provides functions for
playing media, such as play, pause, reset, and so on. If the media is a video, then a MediaView object must
be created to display the video in our scene. MediaView is a Node , so it can be used just like any other node
in the scene, meaning it can be translated, can be animated, or can even have an effect applied to it.
Keep in mind that for both audio and video JavaFX does not provide a widget for starting and stopping
media. It is up to the developer to create actual start and stop nodes, which the user can click.
The javafx.scene.media package includes a few other classes not used in this simple example.
These other classes allow the developer to get some additional details about a particular piece of media,
specifically, details about tracks.
You might have noticed in this simple example that the movie file was not read from the JAR file like
images often are. This is because of a bug in JavaFX; let's hope this issue will be addressed in the next
release of JavaFX. If you are looking at the accompanying source code, you will notice that I included the
movie file in the source code. This is so you can run this example if you want; simply copy the movie file
to somewhere on you local hard drive, and change the URI accordingly.
So, the good news is that JavaFX has pretty good media support and the API is very easy to use.
Unfortunately, the JavaFX media API provides no way to get access to the content of the media
programmatically. The next section explores how we can use the Java Sound API to get the data we need
out of an audio file.
Java Sound
One of the strengths of the JavaFX platform is that it runs on top of the Java platform. This means that all
the functionality that comes with the JVM is available to your JavaFX application. This also means that
all the thousands of libraries written in Java are also available. Since we can't use JavaFX's media
package to create an audio visualization, we have to find another library to do our work. When it comes
to media support, Java is as capable as many other platforms and includes several ways of playing a
sound file. In fact, if you are developing a JavaFX application for the desktop, you have available at least
four APIs from which to choose:
JavaFX media classes
Java Media Framework (JMF) API
AudioClip API
Java Sound
I found it very interesting that these APIs seem to support different formats of music files. I do not
have a good explanation for this, but be warned that Java's codec support is a wonderland of confusion.
For the examples in this chapter, we will be using an MP3 file. (I had some trouble getting all MP3 files to
work with Java Sound, but this one works.)
Search WWH ::




Custom Search