gpt4 book ai didi

java - JAVA中双向通信中的语音中断

转载 作者:太空宇宙 更新时间:2023-11-04 12:58:46 25 4
gpt4 key购买 nike

我在JAVAFX中开发了一个桌面语音聊天应用程序。但在语音聊天中,声音会在连续的时间间隔内受到干扰。任何人都可以帮助我解决这个问题。下面提供了代码。提前致谢。

我的服务器机器代码

public void startCalling()
{
inAudioThread = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
InputStream in = socket.getInputStream();
byte[] buff = new byte[getBufferSize()];
Thread playSound = new Thread();
while((in.read(buff, 0, buff.length)) != -1)
{
playAudio(buff,playSound);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
});

outAudioThread = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
serverSocket= new ServerSocket(9092);
serverSocket.setReuseAddress(true);
socket = serverSocket.accept();

inAudioThread.start();

AudioFormat format = getAudioFormat();
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
tLine = (TargetDataLine)AudioSystem.getLine(info);
tLine.open(format);
tLine.start();

byte buffer[] = new byte[getBufferSize()];

out = new ByteArrayOutputStream();
bufferedOutputStream = new BufferedOutputStream(socket.getOutputStream());

running = true;
try
{
while(running)
{
int count = tLine.read(buffer, 0, buffer.length);
if (count > 0)
{
bufferedOutputStream.write(buffer, 0, count);
out.write(buffer, 0, count);
}
}
out.close();
bufferedOutputStream.close();
}
catch(IOException e)
{

}
}
catch(IOException | LineUnavailableException e)
{

}
}
});

outAudioThread.start();
}

服务器端和客户端的常用函数

public AudioFormat getAudioFormat()
{
AudioFormat.Encoding encoding = AudioFormat.Encoding.PCM_SIGNED;
float sampleRate = 44100.0f;
int sampleSizeInBits = 16;
int channels = 2;
int frameSize = (sampleSizeInBits / 8)* channels;
boolean bigEndian = true;

return new AudioFormat(encoding, sampleRate, sampleSizeInBits, channels, frameSize,sampleRate,bigEndian);
}
public int getBufferSize()
{
return (int) getAudioFormat().getSampleRate()* getAudioFormat().getFrameSize();
}

客户端代码与 startCalling() 函数相同,但行

serverSocket= new ServerSocket(9092);
serverSocket.setReuseAddress(true);
socket = serverSocket.accept();

replaced with **socket = new socket("192.168.8.100",9092);**.

谁能帮我解决语音中断的问题。再次提前致谢

最佳答案

不能保证您每次都能填满缓冲区。在您的 IN 线程中,您错误地认为每次都会读取整个缓冲区。

相反,您必须捕获读取的字节数,如下所示:

while( (bytesRead = in.read(buf)) != -1 ) {
//play audio from buffer *bytesRead* bytes at a time
}

您可以使用IOUtils from Apache Commons它具有读取缓冲区直到缓冲区已满的方法(请参阅 readFully 方法)。

另请注意,在 OUT 线程中 out = new ByteArrayOutputStream();,然后在 while(){} 循环中写入它是不必要的。

关于java - JAVA中双向通信中的语音中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35130681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com