Playing Sound

A game is not so entertaining without sounds. There are three ways of playing sounds in Java.

  • AudioClip class
  • Clip class
  • SourceDataLine

Now let’s see each of them in detail.
[h1]AudioClip[/h1]
The main problem with this class is that it is present in the applet package and is not usable for applications. There are also hacks to make it work but it is not our main concern. Let’s see an example.


import java.applet.*;

public class Sound extends Applet {

    public void init(){
        AudioClip sound = getAudioClip(getDocumentBase(), "sound.au");
        sound.play();
    }

}

Another problem with this is that since it is a JDK 1.1 class, it may or may not support wav files (Depends based on machine) but works well with au files.
[h1]Clip[/h1]
It is usable in both applets and in applications but it cannot be used for long lengthed files. Here’s an example.


import javax.sound.sampled.*;

public class Sound {

    public static void main(String[] args){
        Clip clip = AudioSystem.getClip();
        AudioInputStream inputStream = AudioSystem.getAudioInputStream(Sound.class.getResourceAsStream("sound.wav"));
        clip.open(inputStream);
        clip.start();
        System.exit(0);
    }

}

You must call [icode]System.exit()[/icode] to close any daemon threads which are used by the mixer underneath.
[h1]SourceDataLine[/h1]
It works in all modes and is somewhat advanced (Not the toughest stuff!). Here’s an example.


import javax.sound.sampled.*;

public class Sound {

    public static void main(String[] args){
        AudioInputStream in = AudioSystem.getAudioInputStream(Sound.class.getResourceAsStream("sound.wav"));
        AudioFormat format = in.getFormat();
        // Now create the line info
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
        // Now get the line
        SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);
        line.open(format);
        line.start();

        // Time to play the file. We read 512 Kb at once and write it to the line.
        byte[] data = new byte[524288];// 512 Kb
        try {
            int bytesRead = 0;
            while (bytesRead != -1) {
                bytesRead = in.read(data, 0, data.length);
                if (bytesRead >= 0)
                    line.write(data, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // Release the resources and close the line
            line.drain();
            line.close();
        }
        // Exit closing daemon threads
        System.exit(0);
    }

}

Hope this helped you playing sounds in java. Thank you for reading my first article.
[h1]References[/h1]

I’m not sure if I’m just confused or not; but isn’t that 512kb, not 128kb?

Sorry, just mis-commenting. You are right. Changed it.