I am having hard to sample decibels out of microphone of a computer or cellphone I just want to make sure that I'm doing this right both mathematically and physically.
this is the code:
package soundscale;
import java.io.ByteArrayOutputStream;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;
public class SoundScale{
public static void main(String[] args) {
AudioFormat format = new AudioFormat(8000f, 16, 1, true, false); TargetDataLine microphone;
SourceDataLine speakers;
try {
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
microphone = (TargetDataLine) AudioSystem.getLine(info);
microphone.open();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int numBytesRead;
int CHUNK_SIZE = 512;
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();
long number=0;
while (bytesRead < 10000000) {
numBytesRead = microphone.read(data, 0, CHUNK_SIZE);
bytesRead += numBytesRead;
out.write(data, 0, numBytesRead);
speakers.write(data, 0, numBytesRead);
number=convertToLong(data);//converting to unsigned long from data(amplitude)
number=(long) (20*Math.log10(number));//converting to db using amplitude
System.out.println(" db is "+(number));
}
speakers.drain();
speakers.close();
microphone.close();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
public static final long convertToLong(byte[] bytes) {//better way not to lose data
byte sum = 0;
long sum1=0;
for (byte b : bytes) {
sum ^= b;
}
return sum1=Byte.toUnsignedLong(sum);
}
}
My problem is that it seems that I'm getting a sample but I'm not sure I'm using the right formula for calculating this sample.
I hope that someone that knows both physics, math and java could give an answer.
thanks for your help :)