How to resolve the algorithm Record sound step by step in the Java programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Record sound step by step in the Java programming language

Table of Contents

Problem Statement

Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. Therefore, these programs might not record sound in the same format.)

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Record sound step by step in the Java programming language

The provided Java code defines a class named SoundRecorder that captures and records audio from the system's default audio input device. It starts recording for a specified duration and saves the audio data to a WAV file. Here's a detailed explanation of the code:

  1. import Statements: The code imports necessary libraries for audio recording, including javax.sound.sampled for audio input and output, java.io for file handling, and java.util.concurrent for scheduling.

  2. main Method: The program starts with the main method. It creates an instance of SoundRecorder and schedules a task to stop recording after 10 seconds. The scheduler object schedules the finish task and shuts down.

  3. start Method: The start method is responsible for initiating audio recording. It performs the following steps:

    • Creates an AudioFormat object that defines the format of the audio data to be recorded (16-bit PCM, 16 kHz sampling rate, mono channel).
    • Checks if the audio line format is supported by the system. If not, the program exits.
    • Obtains an instance of TargetDataLine using the specified audio format.
    • Opens and starts the TargetDataLine to begin capturing audio data.
    • Creates an AudioInputStream from the TargetDataLine and writes the audio data to a WAV file using AudioSystem.write.
  4. createAudioFormat Method: This method creates the AudioFormat object used to define the audio data's format (sampling rate, bit depth, channels, etc.).

  5. finish Method: The finish method is scheduled to run after 10 seconds. It stops and closes the TargetDataLine, effectively ending the audio recording.

  6. Instance Fields: The class has several instance fields, including:

    • wavFile: The WAV file where the recorded audio data is stored.
    • audioFileType: The audio file format (WAV) used for saving the recording.
    • line: The TargetDataLine object used for capturing audio input.

In summary, the SoundRecorder class demonstrates how to capture and record audio input from the default audio device for a specified duration, saving the recorded audio in a WAV file.

Source code in the java programming language

import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.io.File;

import javax.sound.sampled.AudioFileFormat.*;

public final class SoundRecorder {

    public static void main(String[] args) {
    	SoundRecorder recorder = new SoundRecorder();
        
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.schedule( () -> recorder.finish(), 10, TimeUnit.SECONDS);
        scheduler.shutdown(); 

        recorder.start();
    }   
 
    private void start() {
        try {
            AudioFormat format = createAudioFormat();
            DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
 
            if ( ! AudioSystem.isLineSupported(info) ) {
                System.out.println("Data line format is not supported");
                Runtime.getRuntime().exit(0);
            }            
            
            line = (TargetDataLine) AudioSystem.getLine(info);
            line.open(format);
            line.start(); 
            
            System.out.println("Starting to capture and record audio");
            AudioInputStream audioInputStream = new AudioInputStream(line); 
            AudioSystem.write(audioInputStream, audioFileType, wavFile);             
            
        } catch (LineUnavailableException | IOException exception) {
            exception.printStackTrace(System.err);
        }
    }

    private AudioFormat createAudioFormat() {
        final float sampleRate = 16_000.0F;
        final int sampleSizeInBits = 16;
        final int channels = 1;
        final boolean signed = true;
        final boolean bigEndian = true;
        // Monophonic 16-bit PCM audio format
        return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);
    }

    private void finish() {
        line.stop();
        line.close(); 
        System.out.println("Finished capturing and recording audio");
    }
    
    private TargetDataLine line;
    
    private final File wavFile = new File("SoundRecorder.wav"); 
    private final AudioFileFormat.Type audioFileType = AudioFileFormat.Type.WAVE;    
    
}


  

You may also check:How to resolve the algorithm Character codes step by step in the Smalltalk programming language
You may also check:How to resolve the algorithm Numerical integration/Gauss-Legendre Quadrature step by step in the PL/I programming language
You may also check:How to resolve the algorithm File size step by step in the Liberty BASIC programming language
You may also check:How to resolve the algorithm Find common directory path step by step in the PureBasic programming language
You may also check:How to resolve the algorithm Loops/Downward for step by step in the Sparkling programming language