【问题标题】:How to playback sound simultaneously after recording Java录制Java后如何同时播放声音
【发布时间】:2014-02-12 07:15:07
【问题描述】:

我是编程新手,我想了解更多信息。

我想通过我的麦克风实时录制声音。下面是我的录制代码。

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

有人可以帮我完成我的项目吗?

【问题讨论】:

    标签: java audio real-time


    【解决方案1】:

    谢谢你的回答先生。但我尝试将此行添加到我的代码中并且播放正常

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

    谢谢你的帮助,先生

    【讨论】:

      【解决方案2】:

      为什么不使用 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);
      
      }
      

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-07
        • 1970-01-01
        相关资源
        最近更新 更多