2014-02-12 78 views
1

我是一名編程新手,我想了解更多信息。如何在錄製後同時播放聲音Java

我想從我的實時麥克風錄製聲音。以下是我的錄音代碼。

while (true) { 
    int numBytesRead = line.read(data, 0, data.length); 
    out.write(data, 0, numBytesRead); 
} 

我想有輸入一些代碼和我玩一些數據塊,但幾秒鐘後,大約3秒記錄延遲。另外,當我試圖說話時,它在循環播放我試圖說的

while (true) { 

    int numBytesRead = line.read(data, 0, data.length); 
    out.write(data, 0, numBytesRead); 
    try { 
     byte audio[] = out.toByteArray(); 
     InputStream input = new ByteArrayInputStream(audio); 
     final SourceDataLine line1 = (SourceDataLine) AudioSystem.getLine(info1); 
     final AudioInputStream ais = new AudioInputStream(input, format, audio.length/format.getFrameSize()); 
     int bufferSize = (int) format.getSampleRate() * format.getFrameSize(); 
     line1.open(format); 
     line1.start(); 
     byte buffer[] = new byte[bufferSize]; 
     try { 
      while (true) { 
       numBytesRead = ais.read(buffer, 0, buffer.length); 
       if (numBytesRead == -1) break; 
       line1.write(buffer, 0, numBytesRead); 
      } 
     } catch (IOException e) { 
      System.err.println("I/O problems: " + e); 
      System.exit(-3); 
     } 
    } 

有人可以幫我完成我的項目。

回答

0

你爲什麼不使用剪輯讀取錄製的聲音。

wavdata = out.toByteArray(); 
AudioInputStream ais = new AudioInputStream(new ByteArrayInputStream(wavdata), WAVFormat(), wavdata.length/WAVFormat().getFrameSize()); 
format = ais.getFormat(); 
info = new DataLine.Info(Clip.class, format); 
Clip clip = (Clip) AudioSystem.getLine(info); 
clip.open(ais); 
//this is for playing 
clip.start(); 
//this is for stopping or pause use it on the pause or stop button. 
//clip.stop(); 

,這是WAVFormat()

private AudioFormat WAVFormat() { 

    int channels = 2; 
    Encoding encoding = AudioFormat.Encoding.PCM_SIGNED; 
    float sampleRate = rateconstant; 
    int frameSize = framesize; 
    float frameRate = rateconstant; 
    int sampleSizeInBits = 16; 
    boolean bigEndian = false; 

    return new AudioFormat(encoding, sampleRate, sampleSizeInBits, channels, frameSize, frameRate, bigEndian); 

} 

希望它有助於

1

謝謝你的回答,先生。但我想加入這行來我的代碼和播放工作

while (numBytesRemaining>0){ 
    numBytesRemaining-=line1.write(data,0,numBytesRemaining); 
       } 

感謝你的幫助,先生