Sams Teach Yourself Java 2 in 24 Hours
- Table of Contents
- Copyright
- About the Author
- About the Technical Editor
- Acknowledgments
- We Want to Hear from You!
- Reader Services
- Introduction
- Hour 1. Becoming a Programmer
- Hour 2. Writing Your First Program
- Hour 3. Vacationing in Java
- Hour 4. Understanding How Java Programs Work
- Part II: Learning the Basics of Programming
- Hour 5. Storing and Changing Information in a Program
- Hour 6. Using Strings to Communicate
- Hour 7. Using Conditional Tests to Make Decisions
- Hour 8. Repeating an Action with Loops
- Part III: Working with Information in New Ways
- Hour 9. Storing Information with Arrays
- Hour 10. Creating Your First Object
- Hour 11. Describing What Your Object Is Like
- Hour 12. Making the Most of Existing Objects
- Part IV: Programming a Graphical User Interface
- Hour 13. Building a Simple User Interface
- Hour 14. Laying Out a User Interface
- Hour 15. Responding to User Input
- Hour 16. Building a Complex User Interface
- Part V: Creating Multimedia Programs
- Hour 17. Creating Interactive Web Programs
- Hour 18. Handling Errors in a Program
- Hour 19. Creating a Threaded Program
- Hour 20. Reading and Writing Files
- Part VI: Creating Multimedia Programs
- Hour 21. Using Fonts and Color
- Hour 22. Playing Sound Files
- Retrieving and Using Sounds
- Java Archives
- Workshop: Making Your Computer Talk to You
- Summary
- Q&A
- Quiz
- Activities
- Hour 23. Working with Graphics
- Hour 24. Creating Animation
- Part VII: Appendixes
- Appendix A. Tackling New Features of Java 2 Version 1.4
- Appendix B. Using the Java 2 Software Development Kit
- Appendix C. Programming with the Java 2 Software Development Kit
- Appendix D. Using Sun ONE Studio
- Appendix E. Where to Go from Here: Java Resources
- Appendix F. This Book's Web Site
Retrieving and Using Sounds
Until the introduction of JavaSound in Java 2, all sound capabilities of the Java language were handled through the JApplet class, the superclass of all Java 2 applets. Although this might make you think that sounds are strictly for use in applets, you can use methods of this class to load and play sound files in any of your Java programs.
There are two ways that sounds can be played in a program: as a one-time occurrence or in a repeating loop.
Sounds are loaded from a file that must have a format supported by the JApplet class. Although past versions of the Java language could handle only one sound file format, Java 2 has been extended to handle each of the following formats:
- AU files
- AIFF files
- WAV files
- MIDI files
Each of these formats is a way to digitally represent actual sounds. To create a sound file in one of these formats, the actual sound is recorded by a computer and converted it into a form that can be saved to a file.
The name of these sound formats is used as their filename extensions, so WAV files are saved with the .WAV extension, AU with .AU, and AIFF with .AIFF
Java can also handle three different MIDI-based sound file formats: Type 0 MIDI, Type 1 MIDI, and RMF. These formats break down sound into the musical notes, instruments, and loudness used to create that sound. Each computer that can play MIDI files knows how to represent each of these things when they are encountered.
For example, if a MIDI file contains several musical notes played in a tuba-like sound, the software playing the file will encounter the notes and dutifully call upon its information on what a tuba sounds like and play the notes.
MIDI files are much smaller than their digital counterparts and are great for playing instrumental music and sound effects. What they can't do is represent more complex sounds, such as the spoken voice.
Simple Sound Playback
The simplest way to retrieve and play a sound is through the play() method of the JApplet class.
In an applet, the play() method can be called with two arguments:
- A URL object representing the folder on the World Wide Web that contains the sound file
- A string indicating the name of the file
If the URL object is a specific Web folder, such as http://www.java24hours.com/source, the sound file should be stored in this folder. However, if you move the applet to a new World Wide Web site later, you must change the source code of the program for it to continue working.
A more flexible solution is to use the applet's getCodeBase() method to provide a URL. This method returns the folder that contains the Java applet playing the sound file. As long as you store the applet and sound file in the same folder, the program will work without modification.
The following example retrieves and plays the sound kaboom.au, which is stored in the same place as the applet:
play(getCodeBase(), "kaboom.au");
The play() method retrieves and plays the given sound as soon as possible. You won't see an error message if the sound can't be found—silence is the only indicator that something might not be working as desired.
Loading Sounds into AudioClip Objects
If you want to do other things with a sound file, such as play it repeatedly or start and stop the sound, you must load the file into an AudioClip object. This is handled in an applet with the following two steps:
- Create an AudioClip object without calling a constructor method.
- Give this AudioClip object a value by calling the applet's getAudioClip() method.
The getAudioClip () method can be called with the same two arguments as the applet's play() method: a URL object (or getCodeBase()) and the name of the sound file.
The following statement loads a sound file into the dance object:
AudioClip dance = getAudioClip(getCodeBase(),
"audio/chachacha.wav");
The filename includes a folder reference in this example, so the file chachacha.wav will be loaded from the subfolder audio.
The getAudioClip() method can be used only in an applet. If you want to load a sound file into an application, you must create an AudioClip object and give it a value by calling a class method of the JApplet class.
The class method newAudioClip () can be used to load audio files in an application. You must first create a URL object associated with the file, beginning the URL with the text file: to indicate that it is a local file rather than something accessed over the Internet. Once you have a URL object representing the audio file, you can load it using the JApplet method newAudioClip( URL ). The previous example could be modified for use in an application as follows:
URL dance = new URL("file:audio/chachacha.wav");
AudioClip danceClip = JApplet.newAudioClip(dance);
The reference to the JApplet class indicates that newAudioClip() is a class method. You don't need to create a JApplet object to call this method in an application.
When you work with URL objects, as you do to play audio files in an application, you must enclose the URL constructor in a try-catch block that deals with MalformedURLException exceptions. The URL class throws this exception whenever the URL does not follow the standard format for Internet addresses.
Playing and Looping AudioClip Objects
After you have created an AudioClip object and associated it with a sound file, you can use three of its methods to control how the sound is used.
- The play() method plays the sound once.
- The loop () method plays the sound repeatedly.
- The stop() method stops the sound from playing.
These methods are called without any arguments. Before you call them on an AudioClip object, you should make sure that the object does not have a value of null. This prevents you from trying to use the sound if the getAudioClip() or newAudioClip() methods did not find the sound file. Calling the methods of a null object will result in an error.
If you play more than one sound at a time, Java will automatically mix the sounds together, which enables some interesting effects. An example would be a MIDI file playing as background music while WAV files are used for sound effects in the foreground.
The LaughTrack application in Listing 22.1 consists of two classes: LaughButton,a new kind of clickable button that can laugh when it is clicked, and LaughTrack, a simple frame that contains one of these buttons.
This application uses Java's capability to mix several sound files together, creating a laugh track. If this term is new to you, you're probably one of the people responsible for the declining viewership of broadcast television. While you're off reading books, hiking, building ships-in-a-bottle, and engaging in other enriching pursuits, the rest of us are watching primetime television comedies. On these comedies, canned laughter often is played to make the shows seem more comic than might appear otherwise. This laughter is called a laugh track.
To create a laugh track in the LaughButton class, four different WAV files containing the sound of laughing people will be loaded into AudioClip objects. Each object will then be played in a loop, creating an impromptu laugh track. You'll have to decide if the end result approximates the sound of a television audience in fits of uncontrolled hysterics.
Enter the text of Listing 22.1 using your preferred word processor, and save the file as LaughTrack.java when you're done.
Example 22.1. The Full Source Code of LaughTrack.java
1: import java.applet.*;
2: import java.awt.*;
3: import java.awt.event.*;
4: import java.net.*;
5: import javax.swing.*;
6:
7: public class LaughTrack extends JFrame {
8:
9: public LaughTrack() {
10: super("Laughtrack");
11: setSize(190, 80);
12: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
13: Container content = getContentPane();
14: FlowLayout flo = new FlowLayout();
15: content.setLayout(flo);
16: LaughButton haha = new LaughButton();
17: content.add(haha);
18: setContentPane(content);
19: setVisible(true);
20: }
21:
22: public static void main(String[] arguments) {
23: LaughTrack lt = new LaughTrack();
24: }
25:
26: }
27:
28: class LaughButton extends JButton implements Runnable, ActionListener {
29: AudioClip[] laugh = new AudioClip[4];
30: Thread runner;
31:
32: LaughButton() {
33: super("Start Laughing");
34: addActionListener(this);
35: for (int i = 0; i < laugh.length; i++) {
36: try {
37: URL laughIn = new URL("file:laugh" + i + ".wav");
38: laugh[i] = JApplet.newAudioClip(laughIn);
39: } catch (MalformedURLException e) { }
40: }
41: }
42:
43: public void actionPerformed(ActionEvent event) {
44: String command = event.getActionCommand();
45: if (command == "Start Laughing")
46: startLaughing();
47: if (command == "Stop Laughing")
48: stopLaughing();
49: }
50:
51: void startLaughing() {
52: if (runner == null) {
53: runner = new Thread(this);
54: runner.start();
55: setText("Stop Laughing");
56: }
57: }
58:
59: void stopLaughing() {
60: if (runner != null) {
61: for (int i = 0; i < laugh.length; i++)
62: if (laugh[i] != null)
63: laugh[i].stop();
64: runner = null;
65: setText("Start Laughing");
66: }
67: }
68:
69: public void run() {
70: for (int i = 0; i < laugh.length; i++)
71: if (laugh[i] != null)
72: laugh[i].loop();
73: Thread thisThread = Thread.currentThread();
74: while (runner == thisThread) {
75: try {
76: Thread.sleep(5000);
77: } catch (InterruptedException e) { }
78: }
79: }
80: }
After you have saved LaughTrack.java, compile the application, but don't run it yet.
Before you can test this application, you must download the audio files being used in this project. Four files are required: laugh0.wav, laugh1.wav, laugh2.wav, and laugh3.wav. These are available from this book's Web site at http://www.java24hours.com on the Hour 22 page. Download these files and save them in the same folder as the LaughTrack applet's class file.
When you have downloaded all the files used in the LaughTrack application, run the application.
Figure 22.1 shows the application running. You can click the button to start the laugh track, and click it again when you can't take any more of the racket.
Figure 22.1 Running the LaughTrack application.
If the result sounds anything like a real audience watching a television show being taped, it may explain why the stars of Seinfeld were ready to stop working on such a lucrative TV show. Bret Butler's stress-related departure from Grace Under Fire and similar troubles experienced by other stars also seem more understandable.
The sound playback features of the LaughButton class are running in a thread in Lines 69–79. The thread is started when the startPlaying() method is called and stopped when the stopPlaying() method is called. These calls take place in the event-handling method actionPerformed() in Lines 43–49.
Sound files, like animation, require a lot of processing time, so it's more efficient to place them into one or more threads.
Java Archives | Next Section

Account Sign In
View your cart