Saturday, 28 September 2019

How to capture and record sound using Java Sound API

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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
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 about generic cialis online 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 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.

No comments:

Post a Comment