This article shows you how easy it is to capture sound 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 in to 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 stopper thread): 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.

The above example program is fixed for quick demo purpose. For a reusable sound recording component, see the article: A utility for recording sound in Java.

 

Recommended Book: Core Java, Volume II--Advanced Features (9th Edition) (Core Series)

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