我正在尝试使用以下代码播放声音输入设备的输入。当我使用此代码时,为了获取默认系统设备,我会听到来自计算机麦克风的播放:
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
microphone = (TargetDataLine) AudioSystem.getLine(info);
microphone.open(format);
但是,我希望能够选择一个特定的输入设备,我可以使用以下代码:
microphone = (TargetDataLine) getLine("iTrack Solo");
microphone.open(format);
我做错了吗?这是完整的代码,包括getLine()方法:
public static void main(String[] args) {
AudioFormat format = new AudioFormat(8000.0f, 16, 1, true, true);
TargetDataLine microphone;
SourceDataLine speakers;
try {
microphone = (TargetDataLine) getLine("iTrack Solo");
microphone.open(format);
int numBytesRead;
int CHUNK_SIZE = 1024;
byte[] data = new byte[microphone.getBufferSize() / 5];
microphone.start();
int bytesRead = 0;
DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, format);
speakers = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
speakers.open(format);
speakers.start();
while (bytesRead < 100000) {
numBytesRead = microphone.read(data, 0, CHUNK_SIZE);
bytesRead += numBytesRead;
speakers.write(data, 0, numBytesRead);
}
speakers.drain();
speakers.close();
microphone.close();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
private static Line getLine(String name) {
try {
Mixer.Info[] mixerInfos = AudioSystem.getMixerInfo();
for (Mixer.Info info : mixerInfos) {
Mixer m = AudioSystem.getMixer(info);
if (info.getName().equals(name)) {
Line.Info[] lineInfos = m.getTargetLineInfo();
for (Line.Info lineInfo : lineInfos) {
return m.getLine(lineInfo);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}