private static TargetDataLine targetDataLine ;
private static AudioFormat audioFormat;
public void captureAudio(){
try {
// 構造具有線性 PCM 編碼和給定參數的 AudioFormat。
audioFormat = getAudioFormat();
// 根據指定信息構造數據行的信息對象,這些信息包括單個音頻格式。此構造方法通常由應用程序用於描述所需的行。
// lineClass - 該信息對象所描述的數據行的類
// format - 所需的格式
DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, audioFormat);
// 如果請求 DataLine,且 info 是 DataLine.Info 的實例(至少指定一種完全限定的音頻格式),
// 上一個數據行將用作返回的 DataLine 的默認格式。
targetDataLine = (TargetDataLine) AudioSystem.getLine(dataLineInfo);
// 開啟線程
new CaptureThread().start();
} catch (Exception e){
e.printStackTrace();
System.exit(0);
}
}
class CaptureThread extends Thread {
public void run() {
// 指定的文件類型
AudioFileFormat.Type fileType = null;
// 設置文件類型和文件擴展名
fileType = AudioFileFormat.Type.WAVE;
try {
// format - 所需音頻格式
targetDataLine.open(audioFormat);
// 當開始音頻捕獲或回放時,生成 START 事件。
targetDataLine.start();
// new AudioInputStream(TargetDataLine line):構造從指示的目標數據行讀取數據的音頻輸入流。該流的格式與目標數據行的格式相同,line - 此流從中獲得數據的目標數據行。
// stream - 包含要寫入文件的音頻數據的音頻輸入流
// fileType - 要寫入的音頻文件的種類
// out - 應將文件數據寫入其中的外部文件
AudioSystem.write(new AudioInputStream(targetDataLine),fileType, "new File("D://ss.wav")");
//AudioSystem.write(new AudioInputStream(new ByteArrayInputStream(bt),audioFormat,bt.length / audioFormat.getFrameSize()),fileType,"new File("D://ss.wav")");
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static AudioFormat getAudioFormat() {
// 8000,11025,16000,22050,44100 采樣率
float sampleRate = 8000F;
// 8,16 每個樣本中的位數
int sampleSizeInBits = 16;
// 1,2 信道數(單聲道為 1,立體聲為 2,等等)
int channels = 2;
// true,false
boolean signed = true;
// true,false 指示是以 big-endian 順序還是以 little-endian 順序存儲音頻數據。
boolean bigEndian = false;
// 構造具有線性 PCM 編碼和給定參數的 AudioFormat。
return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed,
bigEndian);
}
// 關閉 targetDataLine
public void closeCaptureAudio(){
targetDataLine.stop();
targetDataLine.close();
}
測試
public static void main(String[] agrs){
system.out.println("測試開始");
Scanner sc = new Scanner(System.in);
String x = sc.nextLine();
if(x . 等於("yes")){
captureAudio(); //開始錄音的方法
}
x = sc.nextLine();
if(x . 等於("no")){
closeCaptureAudio(); //關閉錄音的方法
}
}