How do I save the microphone audio as a proper WAF file?

To save the microphone audio as a proper WAV file, you need to use the AudioSystem.write() method. WAV files contain raw PCM data combined with a header that describes important details, such as the sample rate, number of channels, etc. Java’s javax.sound.sampled package makes it easy to save the audio in this format.


Example: Saving Captured Audio as a WAV File

Here’s how you can save audio directly as a WAV file while using TargetDataLine:

package org.kodejava.sound;

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;

public class MicrophoneToWav {

    public static void main(String[] args) {
        new MicrophoneToWav().start();
    }

    public void start() {
        // Define the audio format
        AudioFormat audioFormat = new AudioFormat(
                AudioFormat.Encoding.PCM_SIGNED, // Encoding
                44100.0f, // Sample rate (44.1kHz)
                16,       // Sample size in bits
                2,        // Channels (stereo)
                4,        // Frame size (16 bits/sample * 2 channels)
                44100.0f, // Frame rate (matches sample rate for PCM)
                false     // Big-endian (false = little-endian)
        );

        // Get and configure the TargetDataLine
        TargetDataLine microphone;
        try {
            microphone = AudioSystem.getTargetDataLine(audioFormat);
            microphone.open(audioFormat);

            File wavFile = new File("D:/Sound/output.wav");

            // Start capturing audio
            microphone.start();
            System.out.println("Recording started... Press Ctrl+C or stop to terminate.");

            // Set up a shutdown hook for graceful termination
            Runtime.getRuntime().addShutdownHook(new Thread(() -> stop(microphone)));

            // Save the microphone data to a WAV file
            writeAudioToWavFile(microphone, wavFile);

        } catch (LineUnavailableException e) {
            e.printStackTrace();
        }
    }

    private void writeAudioToWavFile(TargetDataLine microphone, File wavFile) {
        try (AudioInputStream audioInputStream = new AudioInputStream(microphone)) {
            // Write the stream to a WAV file
            AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, wavFile);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            stop(microphone);
        }
    }

    public void stop(TargetDataLine microphone) {
        if (microphone != null && microphone.isOpen()) {
            microphone.flush();
            microphone.stop();
            microphone.close();
            System.out.println("Microphone stopped.");
        }
    }
}

Explanation

  1. Audio Format:
    • The AudioFormat specifies PCM encoding with a sample rate of 44100 Hz, 16-bit samples, 2 channels (stereo), and little-endian format.
  2. TargetDataLine:
    • A TargetDataLine is used to read audio data from the microphone.
  3. AudioInputStream:
    • The AudioInputStream wraps the TargetDataLine, creating a stream of audio data in chunks.
  4. AudioSystem.write():
    • The AudioSystem.write() method writes the audio stream directly to a .wav file using AudioFileFormat.Type.WAVE.
    • WAV files are chunks of PCM raw data with a proper header. This method handles creating the header for you.
  5. Shutdown Hook:
    • A shutdown hook ensures that resources (like the microphone) are released when the application stops or when the user presses Ctrl+C.
  6. Graceful Stop:
    • The stop() method safely terminates the recording loop and releases resources, such as the TargetDataLine.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.