This article shows you how easy it is to capture sound/audio coming into your computer’s microphone (or line in) and record the captured sound in to a WAV file, with help of Java Sound API. A small example program is provided to illustrate how to record sound for a specified duration. Let’s look at the Java Sound API first.

The package javax.sound.sampled.* is a part of Java Sound API which contains interfaces and classes that are dedicated for processing sampled audio by Java programming language.

Here are the typical steps to capture and record sound into a WAV file:

  •           Define an audio format of the sound source to be captured, using the class AudioFormat.
  •           Create a DataLine.Info object to hold information of a data line.
  •           Obtain a TargetDataLine object which represents an input data line from which audio data can be captured, using the method getLineInfo(DataLine.Info) of the AudioSystem class.
  •           Open and start the target data line to begin capturing audio data.
  •           Create an AudioInputStream object to read data from the target data line.
  •           Record the captured sound into a WAV file using the following method of the class AudioSystem:

write(AudioInputStream, AudioFileFormat.Type, File)

 

Note that this method blocks the current thread until the target data line is closed.

  •           Stop and close the target data line to end capturing and recording.
Here is the source code of a sample program which follows the steps above:

import javax.sound.sampled.*;
import java.io.*;

/**
 * A sample program is to demonstrate how to record sound in Java
 * author: www.codejava.net
 */
public class JavaSoundRecorder {
	// record duration, in milliseconds
	static final long RECORD_TIME = 60000;	// 1 minute

	// path of the wav file
	File wavFile = new File("E:/Test/RecordAudio.wav");

	// format of audio file
	AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;

	// the line from which audio data is captured
	TargetDataLine line;

	/**
	 * Defines an audio format
	 */
	AudioFormat getAudioFormat() {
		float sampleRate = 16000;
		int sampleSizeInBits = 8;
		int channels = 2;
		boolean signed = true;
		boolean bigEndian = true;
		AudioFormat format = new AudioFormat(sampleRate, sampleSizeInBits,
											 channels, signed, bigEndian);
		return format;
	}

	/**
	 * Captures the sound and record into a WAV file
	 */
	void start() {
		try {
			AudioFormat format = getAudioFormat();
			DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

			// checks if system supports the data line
			if (!AudioSystem.isLineSupported(info)) {
				System.out.println("Line not supported");
				System.exit(0);
			}
			line = (TargetDataLine) AudioSystem.getLine(info);
			line.open(format);
			line.start();	// start capturing

			System.out.println("Start capturing...");

			AudioInputStream ais = new AudioInputStream(line);

			System.out.println("Start recording...");

			// start recording
			AudioSystem.write(ais, fileType, wavFile);

		} catch (LineUnavailableException ex) {
			ex.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	/**
	 * Closes the target data line to finish capturing and recording
	 */
	void finish() {
		line.stop();
		line.close();
		System.out.println("Finished");
	}

	/**
	 * Entry to run the program
	 */
	public static void main(String[] args) {
		final JavaSoundRecorder recorder = new JavaSoundRecorder();

		// creates a new thread that waits for a specified
		// of time before stopping
		Thread stopper = new Thread(new Runnable() {
			public void run() {
				try {
					Thread.sleep(RECORD_TIME);
				} catch (InterruptedException ex) {
					ex.printStackTrace();
				}
				recorder.finish();
			}
		});

		stopper.start();

		// start recording
		recorder.start();
	}
}
 

This console-based program will record sound from the microphone for 60 seconds then saves the recorded sound into a file in .wav format under E:/Test/RecordAudio.wav (so make sure you created the parent directory first). You may want to save as .mp3 format, but unfortunately the Java Sound API only supports the .wav format.

You can change the record duration by modifying value of the constant RECORD_TIME at the beginning of the class.

Notice that there are two threads spawn in this program:

    • First thread (main thread): captures and records sound.
    • Second thread (the stopperthread): waits for a specified duration before closing the target data line. And because the main method is blocked by method call AudioSystem.write(), closing the target data line will continues the main method which exits the program.
Compile the program:

javac JavaSoundRecorder.java



Run it:

java JavaSoundRecorder

Output:

Start capturing...

Start recording...

Finished

And check if the file RecordAudio.wav created under E:/Test directory and play it back.

 

Related Java Sound Tutorials:

 

Other Java Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
Download this file (JavaSoundRecorder.java)JavaSoundRecorder.java[Java Sound Recorder]2 kB

Add comment

   


Comments 

#30Jean-Louis Macle2021-03-26 11:34
Thank you very much.
I appreciated the help brought by this code.
Quote
#29Phil2021-01-11 18:12
Is the comments function working? I don't seem to be able to get to past comments. For example, there are buttons for 2 thru 6 but none of them are operating.

My main goal is to see if there were any responses to the common problem that many people are having accessing the microphone on a Mac (and possibly Ubuntu as well).
Quote
#28ravshan2020-12-14 22:39
it works, file is created, but not any sound is captured. os:ubuntu. Does this class use to work on ubuntu?
Quote
#27Trevor2020-05-04 06:28
Hi Nam,

This is great code and it worked for me on Windows 10. However, when I test it with phrases that include ps and ts I find they don't get recorded. For example the word 'put' comes out as 'uh'. The mic is OK on skype etc. I tried changing the sample rate and the sampleSizeInBits and although sampleSizeInBits = 16 reduced the background hiss the problem with recording ps and ts persisted. Any help appreciated.
Quote
#26Kevin2020-04-27 14:02
I am able to successfully run the recorder on Mac, and it produces a sound file, but unfortunately, when I plait there is no sound. Could it be a microphone access problem?
Quote