Java Reference
In-Depth Information
Listing 9-1. Playing an Audio Clip
public class BasicAudioClip extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
final URL resource = getClass().getResource("resources/beep.wav");
final AudioClip clip = new AudioClip(resource.toString());
final Button button = new Button("Bing Zzzzt!");
button.setOnAction((ActionEvent event) -> {
clip.play(1.0);
});
final StackPane stackPane = new StackPane();
stackPane.setPadding(new Insets(10));
stackPane.getChildren().add(button);
final Scene scene = new Scene(stackPane, 200, 200);
final URL stylesheet = getClass().getResource("media.css");
scene.getStylesheets().add(stylesheet.toString());
primaryStage.setTitle("Basic AudioClip Example");
primaryStage.setScene(scene);
primaryStage.show();
}
}
The prerequisite to creating an AudioClip is to create the URI string for the resource to be loaded. In Listing 9-1,
we use the getResource method to return the URI for an audio file embedded in the jar file. The URI is converted to
a String and then passed to the AudioClip constructor. As previously mentioned, the AudioClip constructor loads
the entire sound into memory, decoding it if necessary. If your sound effect files are small, you can store them in an
uncompressed format such as the .wav file we use in this example to avoid the overhead of decoding them. Once a
sound file grows larger than 100 KB or so, you should consider storing it as a compressed MP3 file instead because the
smaller size of the file can more than make up for the overhead of decoding the sound. This is especially true if you are
loading your sound files from a server on the Internet. You should also keep in mind that the AudioClip constructor
will block the current thread until the sound is completely loaded. For this reason, you should consider loading your
sound effects on a background thread if you are loading a lot of files or if the files are large. See the Chapter 7 for
details on using JavaFX's concurrency classes.
Once the AudioClip is constructed, you simply need to call one of its play methods to start a playback. The
sound in Listing 9-1 is played in response to a button click by calling the play method and passing it a volume
parameter of 1.0, which causes the sound to be played at maximum volume. The Button is then added to a StackPane
so that it will automatically remain centered in the Scene . Finally, the Scene is added to the Stage and shown to
the user. Note that the media.css style sheet is applied to the scene. This style sheet is used by all of the sample
applications in this chapter. The style sheet is shown in Listing 9-2.
 
Search WWH ::




Custom Search