DSP tutorial: Buffered audio recording

This example records audio to a .wav file using a memory buffer.

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
102
103
104
105
106
107
108
109
public class AudioRecorder implements Runnable {

    private static final int SAMPLERATE = 8000;
    private static final int BUFFERSIZE = SAMPLERATE*2;
   
    private TargetDataLine tdl;
    private FileOutputStream fileOutputStream;

    AudioRecorder(final TargetDataLine tdl, final FileOutputStream fileOutputStream) {
        this.tdl = tdl;
        this.fileOutputStream = fileOutputStream;
    }

    @Override
    public void run() {
        byte[] abBuffer = new byte[BUFFERSIZE];

        ByteArrayOutputStream baos = new ByteArrayOutputStream(); // this will store sound data

        tdl.start();

        try {
            while (!Thread.interrupted()) {
                // waiting for the buffer to get filled
                while (tdl.available() < tdl.getBufferSize() * 0.5)
                    Thread.sleep(0, 1); // without this, the audio will be choppy
   
                int bytesRead = tdl.read(abBuffer, 0, tdl.available());
                baos.write(abBuffer, 0, bytesRead);
                System.out.println("Captured " + bytesRead + " bytes.");
            }
        } catch (InterruptedException e) {
        }

        tdl.stop();
        tdl.close();

        // now writing the stored data into a .wav format file
        byte[] abData = baos.toByteArray();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(abData);

        AudioInputStream audioInputStream = new AudioInputStream(byteArrayInputStream, tdl.getFormat(), abData.length / tdl.getFormat().getFrameSize());
        try {
            AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, fileOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            audioInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        AudioFormat audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, SAMPLERATE, 16, 1, 2, SAMPLERATE, false);
        DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat, BUFFERSIZE);

        TargetDataLine targetDataLine = null;
        try {
            targetDataLine = (TargetDataLine) AudioSystem.getLine(info);
            targetDataLine.open(audioFormat, BUFFERSIZE);
            System.out.println("Buffer size: " + targetDataLine.getBufferSize());
        } catch (LineUnavailableException e1) {
            e1.printStackTrace();
        }

        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream("output.wav");
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }

        // creating the recorder thread from this class' instance
        AudioRecorder audioRecorderDirect = new AudioRecorder(targetDataLine, outputStream);
        Thread audioRecorderThread = new Thread(audioRecorderDirect);

        // we use this to read line from the standard input
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Press ENTER to start recording!");
        try {
            br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }

        audioRecorderThread.setPriority(Thread.MAX_PRIORITY);
        audioRecorderThread.start();

        System.out.println("Recording... press ENTER to stop recording!");
        try {
            br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }

        audioRecorderThread.interrupt();

        try {
            // waiting for the recorder thread to stop
            audioRecorderThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Recording stopped.");
    }
}

download (mirror2) (6.1 kb, 27 dls, today: 0)

Name (required)
E-mail (required - never shown publicly)
Webpage URL
Comment:
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> in your comment.

Trackback responses to this post

About me

Nonoo
I'm Nonoo. This is my blog about music, sounds, filmmaking, amateur radio, computers, programming, electronics and other things I'm obsessed with. ... »

Twitter

Listening now

My favorite artists