如何使用java代码控制麦克风开关功能?我需要控制麦克风开启的时间。 我尝试在 java 中使用以下代码:
final AudioFormat format = getFormat();//getformat() has the audio format
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
final TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format); //open mic for input
line.start();
byte[] buffer = new byte[1048576];
OutputStream out = new ByteArrayOutputStream();//output the audio to buffer
boolean running = true;
try {
while (running) {
int count = line.read(buffer, 0, buffer.length);
running=false;
if (count > 0) {
out.write(buffer, 0, count);
}
}
out.close();
} catch (IOException e) {
System.out.println("Error");
System.err.println("I/O problems: " + e);
System.exit(-1);
}
但这基本上取决于缓冲区的大小。 while 循环每次可以输入 30 秒的音频。 我只需要 10 秒的样本输入。 有帮助吗??谢谢。:)
最佳答案
您似乎正试图通过缓冲区的大小来控制麦克风的持续时间。我很确定这不是常见的做法。通常使用大小为几分之一秒的缓冲区(以保持较低的延迟),并反复迭代它。要控制开放式读取或播放操作的持续时间,更常见的做法是更改“running” boolean 值。
因此,代码从循环外部更新“running” boolean 值,并且当循环注意到有停止请求时,读取循环结束。
关于如何获得打开或不打开麦克风的许可,我不是很清楚。我知道 java 声音教程谈论它。
http://docs.oracle.com/javase/tutorial/sound/capturing.html
在他们的示例中,他们使用 boolean 值“stopped”来控制何时结束录制循环。
关于java - 硬件麦克风控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9749810/