Monitoring audio levels in real time is useful for applications like voice recorders, streaming tools, or any app that displays a volume meter. In Java, this is possible using the javax.sound.sampled package, specifically with the TargetDataLine class.
In this post, you’ll learn how to:
- Capture audio input from a microphone
- Convert it into byte data
- Calculate the current audio level (amplitude)
- Display the level in real time (console bar graph style)
Step 1: Setup Required Imports
import javax.sound.sampled.*;
Step 2: Open the Microphone (TargetDataLine)
You’ll need to configure and open a TargetDataLine with a supported audio format:
AudioFormat format = new AudioFormat(44100.0f, 16, 1, true, true);
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format);
line.start();
Step 3: Read and Analyze Audio Data in Real Time
We’ll continuously read short chunks of audio and calculate the volume level based on the root-mean-square (RMS) of the signal.
byte[] buffer = new byte[1024];
int bytesRead;
System.out.println("Monitoring audio levels... (Ctrl+C to stop)");
while (true) {
bytesRead = line.read(buffer, 0, buffer.length);
// Convert bytes to amplitude
double sum = 0.0;
for (int i = 0; i < bytesRead; i += 2) {
// Convert byte pair to int
int sample = (buffer[i] << 8) | (buffer[i + 1] & 0xFF);
sum += sample * sample;
}
double rms = Math.sqrt(sum / ((double) bytesRead / 2));
double db = 20 * Math.log10(rms); // Convert to decibels
// Visualize as a simple bar
int level = (int) (db + 50); // Normalize range
level = Math.max(0, Math.min(50, level));
System.out.println("[" + "*".repeat(level) + "]");
}
Step 4: Clean Up
You should close the audio line when you’re done:
line.stop();
line.close();
Notes and Tips
- The audio input format is 44.1 kHz, 16-bit, mono, signed, big-endian. You can change it to suit your needs.
- The loop runs indefinitely. You may want to run it on a background thread and provide a stop condition.
- For better GUI visualization, consider integrating with Swing or JavaFX.
Summary
You’ve just created a simple Java program that listens to microphone input and prints real-time audio level feedback. This can be used as the foundation for:
- Voice activity detection
- Audio visualizers
- Mute detection
- Noise level meters


