Reputation: 87
I have a thread where I am reading data from TargetDataLine (microphone) and writing it to a ByteArrayOutputStream. I have a little "timer" because I want to record sound for 10 ms and then pass the captured data to another object. No problems so far, this code captures audio for 10 ms and passes the data. But sometimes, the while loop takes ~130 ms... Anyone out there who knows why this happens? Here is my code:
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
}
}
Upvotes: 2
Views: 1298
Reputation: 7910
I recommend reading the linked article. It talks about the various ways Java makes "real time" audio difficult. There's not only aspects due to interruptions from garbage collection and the time splicing via parallel threads done by the JVM, but code can take differing amounts of time to execute depending on whether it is being interpreted or is in memory.
"REAL-TIME, LOW LATENCY AUDIO PROCESSING IN JAVA" http://quod.lib.umich.edu/cgi/p/pod/dod-idx?c=icmc;idno=bbp2372.2007.131
If you wish to get exactly 10msec, the best way is to count samples. You know the sample rate of your input, yes? If it were 44100 fps, 10msec would be 441 samples long.
Upvotes: 1