我有一个线程,我正在从TargetDataLine (麦克风)读取数据,并将其写入ByteArrayOutputStream。我有一个小的“计时器”,因为我想录制10ms的声音,然后将捕获的数据传递给另一个对象。到目前为止没有问题,这段代码捕获10ms的音频并传递数据。但有时,while循环需要大约130毫秒...有没有人知道为什么会这样?下面是我的代码:
while (true) {
byte tempBuffer[] = new byte[2];
try {
byteArrayOutputStream = new ByteArrayOutputStream();
start = System.nanoTime();
double recording = System.nanoTime();
// Get microphone input
while (System.nanoTime() - start <= 10 * 1000000) {
int count = targetDataLine.read(tempBuffer, 0,
tempBuffer.length);
if (count > 0) {
byteArrayOutputStream.write(tempBuffer, 0, count);
}
}
byteArrayOutputStream.close();
LLCapturedData.push(byteArrayOutputStream.toByteArray());
byteArrayOutputStream.flush();
// Tell observers, that input is captured
setChanged();
notifyObservers();
} catch (Exception e) {
// TODO
}
}发布于 2013-04-25 00:29:43
我推荐阅读链接的文章。它谈到了Java使“实时”音频变得困难的各种方式。这不仅仅是由于垃圾收集的中断和JVM通过并行线程进行的时间拼接造成的,而且代码可能需要不同的时间来执行,这取决于它是正在被解释还是在内存中。
“实时、低延迟的JAVA音频处理”http://quod.lib.umich.edu/cgi/p/pod/dod-idx?c=icmc;idno=bbp2372.2007.131
如果你想精确到10毫秒,最好的方法是对样本进行计数。你知道你输入的采样率,对吧?如果它是44100帧/秒,10毫秒将是441个样本长度。
https://stackoverflow.com/questions/16187711
复制相似问题