簡體   English   中英

錄制Java后如何同時播放聲音

[英]How to playback sound simultaneously after recording 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);
        }
    }

有人可以幫我完成我的項目嗎?

謝謝您的回答,先生。 但是我嘗試將這一行添加到我的代碼中,並且播放正常

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

謝謝您的幫助先生

為什么不使用Clip讀取錄音。

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);

}

希望能幫助到你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM