0

我很难从计算机或手机的麦克风中采样分贝,我只是想确保我在数学和物理上都正确地做到了这一点。

这是代码:

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);
 }

 }

我的问题是,我似乎得到了一个样本,但我不确定我是否使用了正确的公式来计算这个样本。

希望懂物理、数学和java的人能给出答案。

感谢您的帮助 :)

4

0 回答 0