Ale*_*lov 6 java audio javasound
我有一个简单的捕获/回放Swing应用程序,必须检测是否没有适当的麦克风连接到计算机并警告用户.经过大量的摆弄后,我找到了唯一的解决方案,让我能够检测到新连接或移除的麦克风:
com.sun.media.sound.JDK13Services.setCachingPeriod(0);
private static boolean isMicrophoneAvailable() {
try {
if (!AudioSystem.isLineSupported(Port.Info.MICROPHONE)) {
log.debug("NO MICROPHONE FOUND");
return false;
} else {
log.debug("MICROPHONE FOUND");
return true;
}
} catch (IllegalArgumentException e) {
log.debug("INCONSISTENT");
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
在后台线程中调用如下:
new Thread() {
public void run() {
while(!thisFrame.isClosed()){
if(isMicrophoneAvailable() == true){
//OK
}else{
//WARN
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
Run Code Online (Sandbox Code Playgroud)
问题是尽管使用所描述的方法正确地检测设备,但是不刷新基础线的列表.也就是说,当程序启动并且稍后连接设备时,在尝试录制声音时会抛出以下异常:
java.lang.IllegalArgumentException: No line matching interface TargetDataLine supporting format PCM_SIGNED 44100.0 Hz, 16 bit, stereo, 4 bytes/frame, big-endian is supported.
Run Code Online (Sandbox Code Playgroud)
有没有办法让AudioSystem的行列表刷新?也许类似于JDK13Services一开始就使用的解决方法,以避免缓存?
更新:抛出异常的代码:
AudioFormat format = formatControls.getDefaultFormat();
DataLine.Info info = new DataLine.Info(TargetDataLine.class,format);
try {
line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format, line.getBufferSize());
} catch (LineUnavailableException ex) {
shutDown("No audio input device available. Please make sure that a microphone is attached to your computer");
return;
} catch (Exception ex) {
log.error(ex.toString());
shutDown(ex.toString());
return;
}
Run Code Online (Sandbox Code Playgroud)
和例外本身:
java.lang.IllegalArgumentException: No line matching interface TargetDataLine supporting format PCM_SIGNED 44100.0 Hz, 16 bit, stereo, 4 bytes/frame, big-endian is supported.
Run Code Online (Sandbox Code Playgroud)
发布引发异常的代码可能会有所帮助。
我假设您仅使用 Port.Info 来检测麦克风的存在,然后获取数据线进行记录:
TargetDataLine dataLine = (TargetDataLine) AudioSystem.getLine(new DataLine.Info(TargetDataLine.class, audioFormat));
dataLine.open();
dataLine.start();
dataLine.read(b, offset, len);
Run Code Online (Sandbox Code Playgroud)
请注意,如果在您检查是否存在和尝试使用数据线进行录音之间麦克风已物理断开连接,则在断开麦克风连接时您可能仍会遇到类似的异常,但连接麦克风应该不会出现问题。
| 归档时间: |
|
| 查看次数: |
3067 次 |
| 最近记录: |