minte9
LearnRemember



RECORD

Capture audio sound from computer microphone.
 
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.*;

class Recorder {

    public static void main(String[] args) throws
            InterruptedException, LineUnavailableException, IOException {

        AudioFormat format = 
            new AudioFormat(16000, 8, 2, true, true);
        DataLine.Info info = 
            new DataLine.Info(TargetDataLine.class, format);
        
        System.out.println("Start capturing ...");

        TargetDataLine microphone = 
            (TargetDataLine) AudioSystem.getLine(info);       
        microphone.open(format);
        microphone.start();

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

        AudioInputStream stream = new AudioInputStream(microphone);
        File wavFile = new File("/var/www/java/recorder_test.wav");
        AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;
        AudioSystem.write(stream, fileType, wavFile);

        // Ctrl + C ... to stop execution
    }
}
Use a second Thread to limit the record time (main thread is blocked by AudioSystem).
 
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.*;

class Recorder {

    public static void main(String[] args) 
            throws InterruptedException, LineUnavailableException, IOException {

        final int RECORD_TIME = 10 * 1000;

        AudioFormat format = 
            new AudioFormat(16000, 8, 2, true, true);
        DataLine.Info info = 
            new DataLine.Info(TargetDataLine.class, format); // {}

        if (!AudioSystem.isLineSupported(info)) {
            System.out.println("Line not supported");
            System.exit(0);
        }

        System.out.println("Open line ...");

        TargetDataLine microphone = (TargetDataLine) AudioSystem.getLine(info);
        microphone.open(format);
        microphone.start();

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

        AudioInputStream stream = new AudioInputStream(microphone);

        new Thread(() -> { // thread to limit record time
            try { 
                Thread.sleep(RECORD_TIME); 
            } 
            catch(InterruptedException e) {}
            microphone.stop();
            microphone.close();
            System.out.println("Finished");
        }).start();

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

        File wavFile = new File("/var/www/java/recorder_test.wav");
        AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;
        AudioSystem.write(stream, fileType, wavFile);
    }
}
Using SourceDataLine you can play back long sound file (or real-time stream sound).
 
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.*;

class PlayBack {

    public static void main(String[] args) throws UnsupportedAudioFileException, 
            IOException, LineUnavailableException {

        File file = new File("/var/www/java/recorder_test.wav");
        AudioInputStream stream = AudioSystem.getAudioInputStream(file);
        AudioFormat format = stream.getFormat();
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
        SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);

        line.open(format);
        line.start();

        System.out.println("Playback started");

        byte[] buffer = new byte[4096];
        int bytes = -1;
        while((bytes = stream.read(buffer)) != -1) {
            line.write(buffer, 0, bytes);
        }

        line.drain();
        line.close();
        stream.close();

        System.out.println("Playback completed");
    }
}

RENDER

To record and render at the same time, write data from microphone to SourceDataLine speaker.
 
import java.io.IOException;
import javax.sound.sampled.*;

class Recorder {

    public static void main(String[] args) 
            throws InterruptedException, LineUnavailableException, 
                        UnsupportedAudioFileException, IOException {

        System.out.println("Start capturing ...");
        AudioFormat format = new AudioFormat(16000, 8, 2, true, true);
        DataLine.Info info = 
            new DataLine.Info(TargetDataLine.class, format); //{}
        TargetDataLine microphone = (TargetDataLine) AudioSystem.getLine(info);
        microphone.open(format);
        microphone.start();

        System.out.println("Start speaker ...");
        DataLine.Info info2 = 
            new DataLine.Info(SourceDataLine.class, format); //{}
        SourceDataLine speaker = (SourceDataLine) AudioSystem.getLine(info2);
        speaker.open(format);
        speaker.start();

        System.out.println("Start rendering ...");
        byte[] data = new byte[microphone.getBufferSize()];
        int bytes = 0;
        while(true) {
            bytes = microphone.read(data, 0, 1024);
            speaker.write(data, 0, bytes); // Look Here
        }
        
        // Ctrl + C ... to stop execution
    }
}

STORE

Add a second render time thread with time limit and save the file.
 
import java.io.*;
import javax.sound.sampled.*;

class Recorder {

    static Boolean exit = false;
    static int RECORD_TIME = 5 * 60 * 1000; // 5min (~10MB)
    static AudioFormat format = new AudioFormat(16000, 8, 2, true, true);

    public static void main(String[] args) 
            throws InterruptedException, LineUnavailableException, 
                        UnsupportedAudioFileException, IOException {

        System.out.println("Start capturing ...");
        DataLine.Info info = 
            new DataLine.Info(TargetDataLine.class, format); //{}
        TargetDataLine microphone = (TargetDataLine) AudioSystem.getLine(info);
        microphone.open(format);
        microphone.start();

        System.out.println("Start speaker ...");
        DataLine.Info info2 = 
            new DataLine.Info(SourceDataLine.class, format); //{}
        SourceDataLine speaker = (SourceDataLine) AudioSystem.getLine(info2);
        speaker.open(format);
        speaker.start();

        System.out.println("Start thread to limit record time ...");
        new Thread(() -> {
            try { Thread.sleep(RECORD_TIME); } catch(Exception e) {}
            exit = true;
            microphone.stop();
            microphone.close();
            speaker.drain();
            speaker.close();
        }).start();

        System.out.println("Start rendering ...");
        byte[] data = new byte[microphone.getBufferSize()];
        ByteArrayOutputStream outData = new ByteArrayOutputStream();
        int bytes = 0;
        while(!exit) {
            bytes = microphone.read(data, 0, 1024);
            speaker.write(data, 0, bytes);
            outData.write(data, 0, bytes); // Look Here
        }

        System.out.println("Start saving file ...");
        InputStream inputData = new ByteArrayInputStream(outData.toByteArray());
        AudioInputStream streamData = 
          new AudioInputStream(inputData, format, outData.toByteArray().length);
        File wavFile = new File("/var/www/java/recorder_test.wav");
        AudioSystem.write(streamData, AudioFileFormat.Type.WAVE, wavFile);

    }
}
To save file in chunks, reset out data after every chunk saved.
 
import java.io.*;
import javax.sound.sampled.*;

class Recorder {

    static final int RECORD_TIME = 5 * 60 * 1000; // 5min (~10MB)
    static final long START_TIME = System.currentTimeMillis();
    static final int CHUNK_SIZE = 1024 * 1000; // 1 MB

    public static void main(String[] args) 
            throws InterruptedException, LineUnavailableException, 
                        UnsupportedAudioFileException, IOException {

        System.out.println("Start capturing ...");
        AudioFormat format = new AudioFormat(16000, 8, 2, true, true);
        DataLine.Info info = 
            new DataLine.Info(TargetDataLine.class, format); //{}
        TargetDataLine microphone = (TargetDataLine) AudioSystem.getLine(info);
        microphone.open(format);
        microphone.start();

        System.out.println("Start speaker ...");
        DataLine.Info info2 = 
            new DataLine.Info(SourceDataLine.class, format); //{}
        SourceDataLine speaker = (SourceDataLine) AudioSystem.getLine(info2);
        speaker.open(format);
        speaker.start(); 

        System.out.println("Start rendering ...");
        byte[] data = new byte[microphone.getBufferSize()];
        ByteArrayOutputStream outData = new ByteArrayOutputStream();
        
        int bytes = 0;
        int i = 0;
        int totalBytes = 0;
        while(true) {

            long elapsedTime = System.currentTimeMillis() - START_TIME;
            if ( elapsedTime >= RECORD_TIME) {
                microphone.stop();
                microphone.close();
                speaker.drain();
                speaker.close();
                break;
            }

            bytes = microphone.read(data, 0, 1024);
            speaker.write(data, 0, bytes);
            outData.write(data, 0, bytes);

            totalBytes += bytes;
            if (totalBytes % CHUNK_SIZE == 0) { // Look Here

                i = i + 1;
                System.out.println("Start saving chunk no ... " + i);
                InputStream inputData = new ByteArrayInputStream(
                    outData.toByteArray()
                );
                AudioInputStream streamData = new AudioInputStream(
                    inputData, format, outData.toByteArray().length
                );
                File wavFile = new File("/var/www/java/rercorder" + i + ".wav");
                AudioSystem.write(
                    streamData, AudioFileFormat.Type.WAVE, wavFile
                );

                outData = new ByteArrayOutputStream(); // Look Here
            }
        }
    }
}



  Last update: 203 days ago