读取特定频率后,如何使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代替,特别是在希望使用松耦合作为打开或关闭插口的机制的情况下。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...