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();
}
}
}
Java 录音代码
最新推荐文章于 2025-03-25 18:56:15 发布

1888

被折叠的 条评论
为什么被折叠?



