如何使我的Java程序在读取某个频率后立即停止捕获音频



我正在netbeans IDE上用Java创建一个吉他调谐器,我希望我的程序在读取某个频率后立即停止捕获实时音频。下面的代码启动音频捕获,但立即停止。例如,我希望它一达到低E字符串的频率就停止。到目前为止,我已使用此网站寻求帮助:https://docs.oracle.com/javase/tutorial/sound/capturing.html

//libraries
import static java.awt.SystemColor.info;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import static java.lang.System.in;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine.Info;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;

public class AudioInputPractice {
/**
* @param args the command line arguments
* @throws javax.sound.sampled.LineUnavailableException
*/
public int read(byte[] b, int off, int len) throws IOException{
return in.read(b, off, len);
}
public static void main(String[] args){

System.out.println("Starting sound test...");


//audio 
try
{
TargetDataLine line;
AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100, 16, 2, 4, 4100, false);

DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
if (!AudioSystem.isLineSupported(info)) {System.err.println("Line not Supported");}
line = (TargetDataLine)AudioSystem.getLine(info);
line.open();




ByteArrayOutputStream out= new ByteArrayOutputStream();
int numBytesRead;
byte[] data = new byte[line.getBufferSize() / 5];

System.out.println("Starting recording...");

line.start();

numBytesRead = line.read(data, 0 , data.length);
out.write(data, 0, numBytesRead);
}
catch (LineUnavailableException ex) 
{
System.out.println("Error");
}



}
}

您的代码只读取一个缓冲区的数据!

通常的做法是将read命令放入条件while循环中。对于您的条件,它可以是一个简单的布尔值isRunning。当你阅读数据时,你可能会把它送到你的球场分析仪上。

Java教程在使用文件和格式转换器中有一个while循环的例子。这是本文中的第一个主要代码引用。下面显示了一个片段。从TargetDataLine读取类似于从AudioInputStream读取,如示例所示。

// Set an arbitrary buffer size of 1024 frames.
int numBytes = 1024 * bytesPerFrame; 
byte[] audioBytes = new byte[numBytes];
try {
int numBytesRead = 0;
int numFramesRead = 0;
// Try to read numBytes bytes from the file.
while ((numBytesRead = 
audioInputStream.read(audioBytes)) != -1) {
// Calculate the number of frames actually read.
numFramesRead = numBytesRead / bytesPerFrame;
totalFramesRead += numFramesRead;
// Here, do something useful with the audio data that's 
// now in the audioBytes array...
}
} catch (Exception ex) { 
// Handle the error...
}

while中的条件在这里被不同地处理。正如我最初建议的那样,通常使用boolean,特别是在希望使用松耦合作为打开或关闭套管的机制的情况下。

最新更新