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

时间:2017-04-02 20:06:13

标签: python sockets tcp udp voice

如标题中所述,我的程序无法处理超过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

1 个答案:

答案 0 :(得分:0)

您是否尝试过在新用户连接时生成多个线程?然后具有某种控制结构(如信号灯)来控制它们在2之间的动作?

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

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