gpt4 book ai didi

java - Voip UDP 添加序列号(准备丢包)

转载 作者:行者123 更新时间:2023-12-02 03:55:20 25 4
gpt4 key购买 nike

注意:我目前正在学习 UDP 以及 VoIP 系统与 TCP 系统相比有多有效,我已经完成了 TCP,所以请不要评论 TCP 更好等等。

因此,我尝试向数据包添加序列号,以便我可以在服务器端对它们进行排序,并通过重复前面的示例来为任何丢失的数据包做好准备

问题:我读到一个 stackoverflow,说使用 DataOutputStreams 是解决这个问题的好方法,所以我实现了它。然而,当使用代码 dos.writeInt(sequenceNumber++); 时,我得到了可怕的重复爆裂声。我在想问题可能是我发送的字节数。

预先感谢您,任何指点都会很棒

  boolean running = true;
try {
AudioRecorder recorder = new AudioRecorder();
int sequenceNumber = 0;
while (running) {
byte[] tempBuffer = recorder.getBlock();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.write(tempBuffer);
dos.writeInt(sequenceNumber++);

dos.flush();
DatagramPacket sendPacket = new DatagramPacket(baos.toByteArray(), baos.size(), clientIP, PORT);
sending_socket.send(sendPacket);

}
recorder.close();
} catch (Exception e) {
System.out.println("Error" + e);

服务器端:

byte[] buffer = new byte[512];
byte[] temp = new byte[512];
try {
// CODE TO RECEIVE THE AUDIO
AudioPlayer player = new AudioPlayer();
int expectedValue = 0;
while (running) {

//Vector used to store audio blocks (32ms/512bytes each)
Vector<byte[]> voiceVector = new Vector<>();

// creates a new udp packet to receive the audio
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
receiving_socket.receive(packet);

// creates a byte array from the data
byte[] udpPacketBytes = packet.getData();
ByteArrayInputStream baos = new ByteArrayInputStream(udpPacketBytes);

DataInputStream dos = new DataInputStream(baos);

int receivedValue = dos.readInt();
if (receivedValue == expectedValue) {
byte[] filteredByteArray = Arrays.copyOfRange(udpPacketBytes, 4, udpPacketBytes.length - 4);
voiceVector.add(filteredByteArray);

Iterator<byte[]> voiceItr = voiceVector.iterator();

while (voiceItr.hasNext()) {
player.playBlock(voiceItr.next());
}

} else {
// play the previous again
byte[] filteredByteArray = Arrays.copyOfRange(temp, 4, temp.length - 4);
voiceVector.add(filteredByteArray);
Iterator<byte[]> voiceItr = voiceVector.iterator();

while (voiceItr.hasNext()) {
player.playBlock(voiceItr.next());
}

// play the current one
byte[] fba = Arrays.copyOfRange(udpPacketBytes, 4, udpPacketBytes.length - 4);
voiceVector.add(fba);

Iterator<byte[]> vItr = voiceVector.iterator();

while (vItr.hasNext()) {
player.playBlock(vItr.next());
}
}
System.out.println(receivedValue + " " + expectedValue);
expectedValue = receivedValue + 1;
temp = packet.getData();


}
} catch (Exception e) {
System.out.println("yo");
}
//Close the socket
receiving_socket.close();

最佳答案

您正在写入序列号,但没有读取或删除它,因此您的序列号最终会出现在音频中。

我建议你阅读你所写的相同格式。

关于java - Voip UDP 添加序列号(准备丢包),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35528922/

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