gpt4 book ai didi

python - 简单的多客户端语音聊天python,当超过两个客户端连接时声音失真

转载 作者:可可西里 更新时间:2023-11-01 02:53:47 24 4
gpt4 key购买 nike

如标题所述,我的程序无法处理超过 2 个客户端。声音失真且断断续续,我不知道如何解决。

有没有人知道如何解决这个问题?谢谢!

这是我的服务器:

import socket
import select


class ChatServer:
def __init__(self):

self.CONNECTION_LIST = []
self.chat_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.chat_server_socket.bind(("0.0.0.0", 50000))
self.chat_server_socket.listen(5)

self.CONNECTION_LIST.append(self.chat_server_socket)

print "Server Started!"

def broadcast(self, sock, data):
for current_socket in self.CONNECTION_LIST:
if current_socket != self.chat_server_socket and current_socket != sock:
try:
current_socket.send(data)
except:
pass

def run(self):
while True:
rlist, wlist, xlist = select.select(self.CONNECTION_LIST, [], [])

for current_socket in rlist:
if current_socket is self.chat_server_socket:
(new_socket, address) = self.chat_server_socket.accept()
self.CONNECTION_LIST.append(new_socket)
print "%s connected to the server" % str(address)
else:
try:
data = current_socket.recv(1024)
self.broadcast(current_socket, data)
except socket.error:
print "%s left the server" % str(address)
current_socket.close()
self.CONNECTION_LIST.remove(current_socket)


if __name__ == "__main__":
ChatServer().run()

这是我的客户:

import socket
import pyaudio
import wave
import thread

# record
CHUNK = 1024 # 512
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 20000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 50000))

p = pyaudio.PyAudio()

receive_stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, output=True, frames_per_buffer=CHUNK)
send_stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK)

print("Voice chat running")

def receive_data():
while True:
try:
data = s.recv(1024)
receive_stream.write(data)
except:
pass


def send_data():
while True:
try:
data = send_stream.read(CHUNK)
s.sendall(data)
except:
pass

thread.start_new_thread(receive_data, ())
thread.start_new_thread(send_data, ())

while True:
pass

最佳答案

您是否尝试过在新用户连接时生成多个线程?然后有一些像信号量这样的控制结构来控制它们在两者之间的 Action ?

您的程序似乎正在接收 2 个音频流,并试图在同一个程序中处理和显示它们。这很容易导致重叠和歧义,因为您不知道如何处理这些数据包(TDM?FDM?)。

如果您有多个线程,您可以在处理某些内容之前请求访问信号量,这样您就可以确切地知道处理内容的顺序。无需预测音频数据的处理方式。

关于python - 简单的多客户端语音聊天python,当超过两个客户端连接时声音失真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43172994/

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