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.
AudioClip
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.
1 2 3 4 5 6 7 8 9 10
| 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.
Clip
It is usable in both applets and in applications but it cannot be used for long lengthed files. Here's an example.
1 2 3 4 5 6 7 8 9 10 11 12 13
| 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
to close any daemon threads which are used by the mixer underneath.
SourceDataLine
It works in all modes and is somewhat advanced (Not the toughest stuff!). Here's an 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 32 33 34 35
| 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(); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info); line.open(format); line.start();
byte[] data = new byte[524288]; 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 { line.drain(); line.close(); } System.exit(0); }
} |
Hope this helped you playing sounds in java. Thank you for reading my first article.
References