Java Sound Playback

Hey again. So I was looking around on how to play sounds through Java via Google and I couldn’t many easy to comprehend explanations. There is a lot more to it than is presented here, but for simple play back of a sound file with no “fancy” stuff this is the way to do it. First an explanation, then the code. Playing a sound file is actually rather easy, thanks to the Clip class. First thing you do is create an AudioInputStream from a file, of course this file is YOUR audio file. I just have a constant clip_loc pointing to its location on disk. NOTE: You can also use a URL instead of a file. After we have our AudioInputStream, we create our clip. We use getClip() from the AudioSystem class, then open our AudioInputStream for the clip, then just use the clips start() method to play it. It’s that simple! After that we have a set of empty while loops. These loops just serve to block execution while the clip is playing. ie. keep the program open until the clip finishes playing. If your program will stay open anyways, then you will want to remove these lines and place the clip’s close() method in an appropriate place. After the loops, the clip closes to release resources and we’re done! That simple. Also, you’ll notice the entire code was wrapped in a try statement. Feel free to throw the exceptions instead. Also, I used a generalized catch to handle all the Exceptions. This is not good practice, but it made the code simpler. Really you’d want to catch each exception and handle it individually.

Java Sound Playback Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import javax.sound.sampled.*;
import java.io.File;
/**
 * @author Jeremiah Johnson
 */
public class SoundTest {
    //where our sound file is located
    final static String  clip_loc = "clips\\Godzilla.wav";
    public static void main(String[] args) {
        try {
            //creates the AudioInputStream from our file
            AudioInputStream audio = AudioSystem.getAudioInputStream(new File(clip_loc));
            //Creates the clip opens it for use, then starts it
            Clip clip = AudioSystem.getClip();
            clip.open(audio);
            clip.start();
            /* The next two lines are only needed if your program will not stay
             * open as the clip plays. The first line just is a small pause before
             * the second line. The second line just keeps the program open while
             * the clip plays.
             */
            while(!clip.isRunning());
            while(clip.isRunning()) {
                Thread.yield();
            }
            clip.close(); //clean up
        } catch ( Exception e ) { //Generalized catch-all. Not good practice, but less typing
            System.out.println(e.getMessage());
        }
    }
}

Comments