我是编程新手,我想了解更多。
我想实时录制麦克风的声音。以下是我的录音代码。
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 :(得分:1)
while (numBytesRemaining>0){
numBytesRemaining-=line1.write(data,0,numBytesRemaining);
}
谢谢你的帮助先生
答案 1 :(得分:0)
为什么不使用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);
}
希望有所帮助