一、需求背景
在某些业务场景中,我们可能需要通过Java程序直接操作硬件设备。本文将演示如何用Java调用笔记本电脑麦克风实现录音功能,并将音频数据保存为WAVE格式文件。这个功能可用于开发语音助手、会议录音工具等应用。
二、开发环境
• JDK 1.8+
• IntelliJ IDEA/Eclipse
• 系统要求:Windows/macOS/Linux(需开启麦克风权限)
三、核心代码实现
package com.example.springbootusecase.hardware;
import javax.sound.sampled.*;
import java.io.*;
public class MicrophoneRecorder {
// 音频格式参数
private static final float SAMPLE_RATE = 44100.0f; // 采样率
private static final int SAMPLE_SIZE = 16; // 位深度
private static final int CHANNELS = 1; // 单声道
private static final boolean SIGNED = true; // 有符号
private static final boolean BIG_ENDIAN = false; // 小端序
private TargetDataLine targetDataLine;
public static void main(String[] args) {
MicrophoneRecorder recorder = new MicrophoneRecorder();
try {
System.out.println("开始录音...(10秒后自动停止)");
AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;
File outputFile = new File("recording.wav");
// 开始录音
recorder.startRecording();
// 创建录音线程
Thread recordingThread = new Thread(() -> {
try {
recorder.saveAudio(outputFile, fileType);
} catch (IOException e) {
e.printStackTrace();
}
});
recordingThread.start();
// 录音持续10秒
Thread.sleep(10000);
// 停止录音
recorder.stopRecording();
System.out.println("录音已保存至: " + outputFile.getAbsolutePath());
} catch (LineUnavailableException | InterruptedException e) {
e.printStackTrace();
}
}
// 初始化音频格式
private AudioFormat getAudioFormat() {
return new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
SAMPLE_RATE,
SAMPLE_SIZE,
CHANNELS,
(SAMPLE_SIZE / 8) * CHANNELS,
SAMPLE_RATE,
BIG_ENDIAN
);
}
// 开始录音
public void startRecording() throws LineUnavailableException {
AudioFormat format = getAudioFormat();
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
// 检查系统是否支持该格式
if (!AudioSystem.isLineSupported(info)) {
System.err.println("不支持的音频格式");
System.exit(1);
}
// 获取并打开目标数据线(麦克风)
targetDataLine = (TargetDataLine) AudioSystem.getLine(info);
targetDataLine.open(format);
targetDataLine.start();
}
// 保存音频到文件
public void saveAudio(File file, AudioFileFormat.Type fileType) throws IOException {
AudioInputStream ais = new AudioInputStream(targetDataLine);
AudioSystem.write(ais, fileType, file);
}
// 停止录音
public void stopRecording() {
targetDataLine.stop();
targetDataLine.close();
}
}
相关技术栈:Java Sound API
音频处理
硬件交互
如果遇到其他问题,欢迎在评论区留言讨论! 👍
(注:本文代码在Windows 11 + JDK8环境下测试通过)