SoundServer 音频录制类:
public class SoundServer {
AudioRecord record;
public void startRecordSound() {
try {
record = new AudioRecord();
record.start();
} catch (Exception e) {
LogUtil.error(e);
}
}
public byte[] stopRecordSound() {
if (record != null) {
record.endRecord();
return record.getBuf();
}
return null;
}
}
class AudioRecord extends Thread {
AudioInputStream audioInputStream;
TargetDataLine line;
AudioFileFormat.Type targetType;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf;
AudioRecord() throws Exception {
AudioFormat audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 16000, 8, 1, 1, 16000, false);
DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat);
line = (TargetDataLine) AudioSystem.getLine(info);
line.open(audioFormat);
audioInputStream = new AudioInputStream(line);
targetType = AudioFileFormat.Type.AU;
}
@Override
public void start() {
line.start();
super.start();
}
public void endRecord() {
line.stop();
line.close();
buf = bos.toByteArray();
}
public byte[] getBuf() {
return buf;
}
@Override
public void run() {
try {
AudioSystem.write(audioInputStream, targetType, bos);
} catch (IOException e) {
LogUtil.error(e);
}
}
}
Launcher 测试主类:
public class Launcher {
public static void main(String[] args) throws Exception {
SoundServer ss = new SoundServer();
Scanner sc = new Scanner(System.in);
System.out.println("请输入Start开始:");
String input = sc.nextLine();
if ("start".equalsIgnoreCase(input)) {
ss.startRecordSound();
}
System.out.println("请输入End结束:");
input = sc.nextLine();
if ("end".equalsIgnoreCase(input)) {
byte[] voice = ss.stopRecordSound();
LogUtil.info(voice);
}
}
}