eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments