如何解决读取特定频率后,如何使Java程序停止捕获音频?
我正在netbeans IDE上用Java创建吉他调音器,我希望我的程序在读取特定频率后立即停止捕获实时音频。下面的代码开始音频捕获,但立即停止。例如,我希望它在到达Low 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,data.length);
out.write(data,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
代替,特别是在希望使用松耦合作为打开或关闭插口的机制的情况下。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。