Java Reference
In-Depth Information
Preparing the Audio File
In the source code you will find that a WAV file is provided for use in this example. Before we get into
details of how the code works, I would like to thank J-San & The Analogue Sons for letting me use the
title track of their album One Sound in this example. If you like modern reggae, go check them out at .
You can find the MP3 file used in the example in the folder org/lj/jfxe/chapter9/media of the
accompanying source code. Since it is in the source code, it will be put into the JAR that makes up this
NetBeans project. Since it is in the JAR file, it can be accessed by the running process. However, Java
Sound, like JavaFX, has an issue where sound files cannot be played directly from the JAR. To get around
this, we must read the file out of the JAR and write it to disk someplace. Once the file is written to disk,
we can get Java to play the sound file. Listing 9-2 shows some of the source code from the class
SoundHelper , which is a Java class that is responsible for preparing and playing the sound file.
Listing 9-2. (Partial)
public class SoundHelper extends Observable implements SignalProcessorListener {
private URL url = null;
private SourceDataLine line = null;
private AudioFormat decodedFormat = null;
private AudioDataConsumer audioConsumer = null;
private ByteArrayInputStream decodedAudio;
private int chunkCount;
private int currentChunk;
private boolean isPlaying = false;
private Thread thread = null;
private int bytesPerChunk = 4096;
private float volume = 1.0f;
public SoundHelper(String urlStr) {
try {
if (urlStr.startsWith("jar:")) {
this.url = createLocalFile(urlStr);
} else {
this.url = new URL(urlStr);
} catch (Exception ex) {
throw new RuntimeException(ex);
private File getMusicDir() {
File userHomeDir = new File(System.getProperties().getProperty("user.home"));
File synethcDir = new File(userHomeDir, ".chapter9_music_cache");
File musicDir = new File(synethcDir, "music");
Search WWH ::

Custom Search