我想从扬声器读取音量。但是,我不知道如何获取发送给扬声器的数据。我已经能够使用这种方法并通过从 TargetDataLine 读取数据来为我的麦克风做到这一点。我不知道如何为演讲者做到这一点。我想读取发送到扬声器的数据(可能通过 SourceDataLine?)我尝试使用 SourceDataLine 来获取幅度,但我的示例代码无法正常工作,它一直返回 -1。有什么建议么?示例代码:
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new JFrame();
JProgressBar bar = new JProgressBar();
frame.getContentPane().add(bar);
frame.pack();
//frame.show();
AudioFormat audio = new AudioFormat(8000.0F,16,1,true,false);
//DataLine.Info info = new DataLine.Info(SourceDataLine.class, audio);
DataLine.Info speakerInfo = new DataLine.Info(SourceDataLine.class, audio);
SourceDataLine speaker;
try {
speaker = (SourceDataLine) AudioSystem.getLine(speakerInfo);
speaker.open(audio);
speaker.start();
//Toolkit.getDefaultToolkit().beep();
} catch (LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
//while(true){
System.out.println(speaker.getLevel());
//}
}
public static int calculateRMSLevel(byte[] audioData){
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);
}