1. Overview

In this tutorial, we’ll learn how to play sound with Java. The Java Sound APIs are designed to play sounds smoothly and continuously, even very long sounds.

As part of this tutorial, we’ll play an audio file using Clip and SourceDataLine Sound APIs provided by Java. We’ll also play different audio format files.

In addition, we’ll discuss the pros and cons of each API. Further, we’ll see a couple of third-party Java libraries that can also play sound.

2. Java APIs to Play Sound

In general, the Java Sound APIs present in the javax.sound package provide two ways to playback audio. Between the two approaches, there’s a difference in how the sound file data is specified. The Java Sound APIs can handle audio transport in both a streaming, buffered fashion, and an in-memory, unbuffered fashion. Java’s two most well-known sound APIs are Clip and SourceDataLine.

2.1. Clip API

Clip API is an unbuffered or in-memory sound API for Java. The Clip class is part of the javax.sound.sampled package, and it is useful when reading and playing a short sound file. Before playing back, the entire audio file is loaded into memory, and the user has total control over the playback.

In addition to looping sounds, it also allows users to start playback at a random location.

Let’s first create a sample class, SoundPlayerWithClip, which implements the LineListener interface in order to receive line events (OPEN, CLOSE, START, and STOP) for the playback. We’ll implement the update() method from LineListener to check the playback status:

public class SoundPlayerUsingClip implements LineListener {

    boolean isPlaybackCompleted;
    
    @Override
    public void update(LineEvent event) {
        if (LineEvent.Type.START == event.getType()) {
            System.out.println("Playback started.");
        } else if (LineEvent.Type.STOP == event.getType()) {
            isPlaybackCompleted = true;
            System.out.println("Playback completed.");
        }
    }
}

Secondly, let’s read the audio file from our project’s resource folder. Our resource folder contains three audio files of different formats — namely, WAV, MP3, and MPEG:

InputStream inputStream = getClass().getClassLoader().getResourceAsStream(audioFilePath);

Thirdly, From the file stream, we’ll create an AudioInputStream:

AudioInputStream audioStream = AudioSystem.getAudioInputStream(inputStream);

Now, we’ll create a DataLine.Info object:

AudioFormat audioFormat = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);

Let’s create a Clip object from this DataLine.Info and open the stream, and then call start to start playing the audio:

Clip audioClip = (Clip) AudioSystem.getLine(info);
audioClip.addLineListener(this);
audioClip.open(audioStream);
audioClip.start();

Finally, we’ll need to close any open resource:

audioClip.close();
audioStream.close();

Once the code runs, the audio file will play.

As the audio is preloaded in memory, we have many other useful APIs from which we can benefit.

We can use the Clip.loop method to continuously play the audio clip in a loop.

For example, we can set it to play the audio five times:

audioClip.loop(4);

Or, we can set it to play the audio for an infinite time (or until interrupted):

audioClip.loop(Clip.LOOP_CONTINUOUSLY);

The Clip.setMicrosecondPosition sets the media position. When the clip begins playing the next time, it will start at this position. For example, to start from the 30th second, we can set it as:

audioClip.setMicrosecondPosition(30_000_000);

2.2. SourceDataLine API

SourceDataLine API is a Buffered or Streaming sound API for java. The SourceDataLine class is part of the javax.sound.sampled package, and it can play long sound files that cannot be preloaded into memory.

Using SourceDataLine is more effective when we wish to optimize the memory for large audio files or when streaming real-time audio data. It’s also useful if we don’t know in advance how long the sound is and when it will end.

Let’s first create a sample class and read the audio file from our project’s resource folder. Our resource folder contains three audio files of different formats — namely, WAV, MP3, and MPEG:

InputStream inputStream = getClass().getClassLoader().getResourceAsStream(audioFilePath);

Secondly, from the file input stream, we’ll create an AudioInputStream:

AudioInputStream audioStream = AudioSystem.getAudioInputStream(inputStream);

Now, we’ll create a DataLine.Info object:

AudioFormat audioFormat = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, audioFormat);

Let’s create a SourceDataLine object from this DataLine.Info, open the stream, and call start to start playing the audio:

SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem.getLine(info);
sourceDataLine.open(audioFormat);
sourceDataLine.start();

Now, in the case of SourceDataLine, the audio data is loaded in chunks, and we need to provide the buffer size:

private static final int BUFFER_SIZE = 4096;

Now, let’s read audio data from the AudioInputStream and send it to the SourceDataLine’s playback buffer until its reaches the end of the stream:

byte[] bufferBytes = new byte[BUFFER_SIZE];
int readBytes = -1;
while ((readBytes = audioStream.read(bufferBytes)) != -1) {
    sourceDataLine.write(bufferBytes, 0, readBytes);
}

Finally, let’s close any open resource:

sourceDataLine.drain();
sourceDataLine.close();
audioStream.close();

Once the code runs, the audio file will play.

Here, we don’t need to implement any LineListener interface.

2.3. Comparison Between Clip and SourceDataLine

Let’s discuss the pros and cons of both:

Clip

SourceDataLine

Supports playing from any position in the audio. See setMicrosecondPosition(long) or setFramePosition(int).

Can’t start playing from an arbitrary position in the sound.

Supports playing in the loop (all or part of the sound). see setLoopPoints(int, int) and loop(int).

Can’t play (loop) all or a part of the sound.

Can know duration of the sound before playing. See getFrameLength() or getMicrosecondLength().

Can’t know the duration of the sound before playing.

It’s possible to stop playing back at the current position and resume playing later. see stop() and start()

Can’t stop and resume playing in the middle.

Not suitable and inefficient to playback big audio files as it’s in-memory.

It’s suitable and efficient for playback of long sound files or to stream the sound in real-time.

The Clip’s start() method does play the sound, but it does not block the current thread (it returns immediately), so it requires implementing the LineListener interface to know the playback status.

Unlike the Clip, we don’t have to implement the LineListener interface to know when the playback completes.

It’s not possible to control what sound data is to be written to the audio line’s playback buffer.

It’s possible to control what sound data is to be written to the audio line’s playback buffer.

2.4. Java API Support for MP3 Format

Currently, both Clip and SourceDataLine can play audio files in AIFC, AIFF, AU, SND, and WAV formats.

We can check the supported audio format using AudioSystem:

Type[] list = AudioSystem.getAudioFileTypes();
StringBuilder supportedFormat = new StringBuilder("Supported formats:");
for (Type type : list) {
    supportedFormat.append(", " + type.toString());
}
System.out.println(supportedFormat.toString());

However, we cannot play the popular audio format MP3/MPEG with Java Sound APIs Clip and SourceDataLine. We need to look for some third-party libraries that can play MP3 format.

If we provide the MP3 format file to either Clip or SourceDataLine API, we’ll get the UnsupportedAudioFileException:

javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file
    at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1189)

3. Third-Party Java APIs to Play Sound

Let’s have a look at a pair of third-party libraries that can also play the different audio format files.

3.1. JavaFX Library

JavaFX has Media and MediaPlayer classes that will play MP3 files. It can also play other audio formats like WAV.

Let’s create a sample class and use the Media and MediaPlayer class to play our MP3 file:

String audioFilePath = "AudioFileWithMp3Format.mp3";
SoundPlayerUsingJavaFx soundPlayerWithJavaFx = new SoundPlayerUsingJavaFx();
try {
    com.sun.javafx.application.PlatformImpl.startup(() -> {});
    Media media = new Media(
      soundPlayerWithJavaFx.getClass().getClassLoader().getResource(audioFilePath).toExternalForm());
    MediaPlayer mp3Player = new MediaPlayer(media);
    mp3Player.play();
} catch (Exception ex) {
    System.out.println("Error occured during playback process:" + ex.getMessage());
}

One advantage of this API is that it can play WAV, MP3, and MPEG audio formats.

3.2. JLayer Library

The JLayer library can play audio formats like MPEG formats, including MP3. However, it cannot play other formats like WAV.

Let’s create a sample class using the Javazoom Player class:

String audioFilePath = "AudioFileWithMp3Format.mp3";
SoundPlayerUsingJavaZoom player = new SoundPlayerUsingJavaZoom();
try {
    BufferedInputStream buffer = new BufferedInputStream(
      player.getClass().getClassLoader().getResourceAsStream(audioFilePath));
    Player mp3Player = new Player(buffer);
    mp3Player.play();
} catch (Exception ex) {
    System.out.println("Error occured during playback process:" + ex.getMessage());
}

4. Conclusion

In this article, we learned how to play sound with Java. We also learned about two different Java Sound APIs, Clip and SourceDataLine. Later, we saw the differences between Clip and SourceDataLine APIs, which will help us choose the appropriate one for any use case.

Lastly, we saw some third-party libraries that could also play audio and support other formats, such as MP3.

As always, the example code used in this article is available over on GitHub.