Java Reference
In-Depth Information
It bears repeating that of these three classes, only MediaView is a Node and therefore capable of being inserted
into the scene graph. This means we have taken a slight liberty in showing a set of visual controls associated with the
MediaPlayer class in Figure 9-3 . In reality, you will have to create your own buttons and sliders, wired to MediaPlayer
methods, to allow the user to control the playback of the media in your application. We have plenty of opportunity
to show you how to do this in the examples that follow in this chapter. Let's begin our in-depth look at these media
classes by creating an application that plays audio files.
Playing Audio
Playing audio files involves only the Media and MediaPlayer classes. There is no video to deal with, thus no MediaView
is needed. Listing 9-6 shows the minimum amount of code needed to play audio with JavaFX.
Listing 9-6. A Very Simple Application That Plays an Audio File
public class AudioPlayer1 extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
URL resource = getClass().getResource("resources/keeper.mp3");
Media media = new Media(resource.toString());
MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
primaryStage.setTitle("Audio Player 1");
primaryStage.setWidth(200);
primaryStage.setHeight(200);
primaryStage.show();
}
}
This simplistic application starts by finding the URL of an audio file resource that is packaged within its jar file.
The String form of the resource URL is passed as the source parameter to the Media constructor. The Media class
can also load resources from the Internet or from the local file system just like an AudioClip . Once the Media object
is constructed, it is used to construct a new MediaPlayer and the MediaPlayer 's play method is called to begin
playback. This application has no actual scene to display, so the width and height of the Stage are set to 200 so that
the resulting window will be visible. If your audio needs are no more complicated than loading a sound file and
playing it, your job is now finished. However, the code in Listing 9-6 is not exactly production quality yet.
Once a MediaPlayer is created, its Media object cannot be changed. if you wish to change the song or video
that is currently playing, you must create a new MediaPlayer for the new Media object. Multiple MediaPlayer s can share
one Media object.
Note
 
 
Search WWH ::




Custom Search