DSP tutorial: Simple audio recording
Last modified: November 16th, 2011This example records audio to a .wav file using the built-in Java methods.
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 | public class AudioRecorder implements Runnable { // note that this is declared as static so if we stop/close it, the thread will stop private static TargetDataLine tdl; private File outputFile; AudioRecorder(final TargetDataLine tdl, final File outputFile) { AudioRecorder.tdl = tdl; this.outputFile = outputFile; } @Override public void run() { tdl.start(); try { // this will block until tdl doesn't get closed AudioSystem.write(new AudioInputStream(tdl), AudioFileFormat.Type.WAVE, outputFile); } catch (IOException e) { e.printStackTrace(); } } public void stopRecording() { tdl.stop(); tdl.close(); } public static void main(String[] args) { File outputFile = new File("output.wav"); AudioFormat audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100.0F, 16, 2, 4, 44100.0F, false); DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat); TargetDataLine targetDataLine = null; try { targetDataLine = (TargetDataLine) AudioSystem.getLine(info); targetDataLine.open(audioFormat); } catch (LineUnavailableException e1) { e1.printStackTrace(); } // creating the recorder thread from this class' instance AudioRecorder audioRecorder = new AudioRecorder(targetDataLine, outputFile); Thread audioRecorderThread = new Thread(audioRecorder); // 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.start(); System.out.println("Recording... press ENTER to stop recording!"); try { br.readLine(); } catch (IOException e) { e.printStackTrace(); } audioRecorder.stopRecording(); try { // waiting for the recorder thread to stop audioRecorderThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Recording stopped."); } } |
As you can see, we start a thread to handle the recording. This way we can wait for a keypress to stop recording.
download (4.9 kb)
About me
I'm Nonoo. This is my blog about music, sounds, filmmaking, amateur radio, computers, programming, electronics and other things I'm obsessed with.
... »
Hi, for me it looks like this is just the source code with just a few explanations. Would be nice if there would be more comments. But thx :)