Java 录音代码

import javax.sound.sampled.*;
import java.io.*;
import java.util.Scanner;

public class AudioRecorder {

    private TargetDataLine line;
    private ByteArrayOutputStream out;
    private boolean running = false;

    public AudioRecorder() throws LineUnavailableException {
        // 采样率16000HZ,每个样本16位,单声道
        AudioFormat format = new AudioFormat(16000, 16, 1, true, true);
        DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
        line = (TargetDataLine) AudioSystem.getLine(info);
        line.open(format);
        line.start();
        out = new ByteArrayOutputStream();
    }

    public void startRecording() {
        running = true;
        new Thread(() -> {
            try (AudioInputStream ais = new AudioInputStream(line)) {
                byte[] buffer = new byte[4096];
                while (running) {
                    int bytesRead = ais.read(buffer);
                    if (bytesRead != -1) {
                        out.write(buffer, 0, bytesRead);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public void stopRecording() {
        running = false;
    }

    public void saveAudio(File file) throws IOException {
        byte[] audioData = out.toByteArray();
        try (AudioInputStream ais = new AudioInputStream(
                new ByteArrayInputStream(audioData),
                line.getFormat(),
                audioData.length / line.getFormat().getFrameSize())) {
            AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new FileOutputStream(file));
        }
    }

    public static void main(String[] args) {
        try {
            AudioRecorder recorder = new AudioRecorder();
            recorder.startRecording();

            // 等待用户按下回车键来停止录制
            System.out.println("Press Enter to stop recording...");
            new Scanner(System.in).nextLine(); // 这将阻塞直到用户按下回车键

            recorder.stopRecording();
            recorder.saveAudio(new File("recorded_audio.wav"));

            System.out.println("Recording saved as recorded_audio.wav");

        } catch (LineUnavailableException | IOException e) {
            e.printStackTrace();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值