2
我試圖找到麥克風輸入的最大音量,因爲我試圖找出平均聲音有多大,所以我的程序可以通過音量識別它。有效值的計算方法是從這個網站(https://forums.oracle.com/forums/thread.jspa?threadID=1270831),我只是想弄清楚如何一切正常......計算麥克風音量(試圖找到最大值)
問題是,無論我使RMS級別多少噪音每次輸出0 !所以我要麼將targetDataLine設置爲完全錯誤,並且不能捕獲音頻...或者我在其他地方做了錯誤的事情。
這是我到目前爲止有:
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;
public class MicrophoneTesting {
public MicrophoneTesting() {
// TODO Auto-generated constructor stub
}
protected static int calculateRMSLevel(byte[] audioData)
{ // audioData might be buffered data read from a data line
long lSum = 0;
for(int i=0; i<audioData.length; i++)
lSum = lSum + audioData[i];
double dAvg = lSum/audioData.length;
double sumMeanSquare = 0d;
for(int j=0; j<audioData.length; j++)
sumMeanSquare = sumMeanSquare + Math.pow(audioData[j] - dAvg, 2d);
double averageMeanSquare = sumMeanSquare/audioData.length;
return (int)(Math.pow(averageMeanSquare,0.5d) + 0.5);
}
public static void main(String[] args){
// Open a TargetDataLine for getting microphone input & sound level
TargetDataLine line = null;
AudioFormat format = new AudioFormat(8000, 0, 1, true, true);
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); // format is an AudioFormat object
if (!AudioSystem.isLineSupported(info)) {
System.out.println("The line is not supported.");
}
// Obtain and open the line.
try {
line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format);
} catch (LineUnavailableException ex) {
System.out.println("The TargetDataLine is Unavailable.");
}
Timer t = new Timer(); // I used a timer here, code is below
while(t.seconds < 2){
byte[] bytes = new byte[line.getBufferSize()/5];
line.read(bytes, 0, bytes.length);
System.out.println("RMS Level: " + calculateRMSLevel(bytes));
}
}
}
定時器代碼:
public class Timer implements Runnable{
int seconds;
Thread t;
public Timer() {
this.seconds = 0;
t = new Thread(this, "Clap Timer");
t.start(); // Start the thread
}
@Override
public void run() {
// TODO Auto-generated method stub
while(seconds < 2)
{
//Wait 1 second
try {
Thread.sleep(1000);
}
catch(Exception e) {
System.out.println("Waiting interupted.");
}
seconds++;
}
}
}
@ user2247192可以回答你自己的問題,但你應該用正確的答案格式來寫,就像你回答其他人的問題一樣。留下諸如「愚蠢的錯誤!」之類的東西並告訴應該在哪裏添加該行(在'line.open()'?之後),並且最好也是爲什麼需要它(在這種情況下,它可能很明顯)。那麼這是一個很好的答案,您可以稍後再回來接受它。 – hyde 2013-04-08 07:05:18
請注意......我在line.open()的下方添加了「line.start()」 – Riptyde4 2013-04-08 21:34:48