2016-02-28 106 views
1

我試圖通過使用此代碼的Java soundApi記錄錯誤

import java.io.File; 
import java.io.IOException; 

import javax.sound.sampled.AudioFileFormat; 
import javax.sound.sampled.AudioFormat; 
import javax.sound.sampled.AudioInputStream; 
import javax.sound.sampled.AudioSystem; 
import javax.sound.sampled.DataLine; 
import javax.sound.sampled.TargetDataLine; 

public class Main { 

    public static void main(String[] args) { 
     System.out.println("Say what you see.."); 

     try { 
      AudioFormat format = new AudioFormat(
        AudioFormat.Encoding.PCM_SIGNED, 16000, 8, 1, 4, 16000, 
        false); 

      DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); 
      if (!AudioSystem.isLineSupported(info)) 
       System.out.println("Line not Supported"); 
      final TargetDataLine targetLine = (TargetDataLine) AudioSystem 
        .getLine(info); 
      targetLine.open(); 

      System.out.println("Recording"); 
      targetLine.start(); 

      Thread thread = new Thread() { 

       @Override 
       public void run() { 
        AudioInputStream audioStream = new AudioInputStream(
          targetLine); 
        File audioFile = new File("record.wav"); 
        try { 
         AudioSystem.write(audioStream, 
           AudioFileFormat.Type.WAVE, audioFile); 
        } catch (IOException ioe) { 
         ioe.printStackTrace(); 
        } 
        System.out.println("stopped recording"); 
       } 

      }; 
      thread.start(); 
      Thread.sleep(5000); 
      targetLine.stop(); 
      targetLine.close(); 
      System.out.println("Done"); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 

當我運行它,我總是得到這個錯誤錄製16kHz的單聲道.wav文件:

Line not Supported 
java.lang.IllegalArgumentException: No line matching interface TargetDataLine supporting format PCM_SIGNED 16000.0 Hz, 8 bit, mono, 4 bytes/frame, is supported.at javax.sound.sampled.AudioSystem.getLine(AudioSystem.java:476)at Main.main(Main.java:29) 

PS:我用AudioFormat的不同參數對它進行了多次測試它只在我嘗試了這些參數是立體聲和44.1khz時才起作用

AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,44100,16,2,4,44100,false); 

回答

2

您必須指定一個與TargetDataLine支持的格式匹配的AudioFormat

例如我的Mac上的麥克風支持:

Supported Audio Formats

「未知的採樣率」是指採樣率沒有關係。

我在這裏看到的主要區別是,你指定每幀4個字節,對於8位單聲道,這應該是每幀1個字節。

+0

愛你的男人:D,工作就像一個魅力! – Beeee