我正在尝试通过UDP套接字发送语音数据,但是客户端接收的语音数据断断续续。
目前,我在同一台计算机上运行server.py
和client.py
。也许这可能是问题所在?另一种可能性是发送语音数据的短包,然后播放得足够快,以至于它结束了一小会儿。这也可能是硬件问题(我目前正在使用2015 Macbook Pro(。
我已经在TCP中实现了这个程序,它完美地工作。但是,该程序的主要目的是处理更多的客户端。
我将尝试在不同的机器上运行这些脚本,看看它是否有效。期望的结果是以流畅的方式播放接收到的语音数据,而不是以断断续续的形式播放音频。
server.py
import socket
import pyaudio
import threading
from os import system
system('clear')
# Socket
host = socket.gethostbyname(socket.gethostname())
port = 6000
buffer = 2048
clients = []
# Audio
audio = pyaudio.PyAudio()
chunk = int(1024 * 4)
def client_listener():
while True:
data, address = host_socket.recvfrom(buffer)
if address not in clients:
print(f'New client: {address[0]}:{address[1]}')
clients.append(address)
print(clients)
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as host_socket:
try:
host_socket.bind((host, port))
print(f'Server hosted at {host}:{port}n')
print('Starting listener thread...')
listener_thread = threading.Thread(target=client_listener)
listener_thread.daemon = True
listener_thread.start()
print('Listener thread started!')
print('Initiating microphone...')
stream = audio.open(format=pyaudio.paInt16,
channels=1,
rate=44100,
input=True,
frames_per_buffer=chunk)
print('Recording!')
while True:
voice_data = stream.read(chunk, exception_on_overflow=False)
for client in clients:
host_socket.sendto(voice_data, client)
except socket.error as error:
print(str(error))
stream.close()
host_socket.close()
except KeyboardInterrupt:
stream.close()
host_socket.close()
finally:
stream.close()
host_socket.close()
client.py
import socket
import pyaudio
from os import system
# Socket
host = socket.gethostbyname(socket.gethostname())
port = 6000
system('clear')
# Audio
audio = pyaudio.PyAudio()
chunk = int(1024 * 4)
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as client_socket:
try:
client_socket.sendto(' '.encode('utf-8'), (host, port))
stream = audio.open(format=pyaudio.paInt16,
channels=1,
rate=44100,
output=True,
frames_per_buffer=chunk)
while True:
voice_data = client_socket.recv(chunk)
print(voice_data)
stream.write(voice_data)
except socket.error as error:
print(str(error))
stream.close()
client_socket.close()
except KeyboardInterrupt:
stream.close()
client_socket.close()
finally:
stream.close()
client_socket.close()
从网络的角度来看,我可以看到为什么TCP在UDP上完美运行。传输控制协议是一种纠错协议 - 又名无损 - 并跟踪正在发送的内容以确定错误。如果发送的数据由于某种原因不完整,它会要求重新发送。用户数据报协议不是纠错和更多的流 - 一个接一个。我不了解python,但我建议如果你创建自己的纠错方法,那么如果你要使用UDP,它将获得与TCP相同的效果。类似于MD5检查的东西,接收者会知道"这个信息包是完整的"。
您需要某种抖动缓冲器 - 看看一些开源的 SIP/RTP 应用,因为此功能在实践中可能相当复杂,还要处理数据包重新排序,再加上某种 PLC 来补偿数据包丢失和自适应延迟,具体取决于实际网络抖动。如果您有多个设备,也很难避免时钟偏差。
我也不完全确定python是否是具有大量客户端的服务器的好选择。我想python + pjsip更典型。