架构

需要一台服务器运行服务器脚本,将所有客户端的数据包互相转发。

依赖 PyAudio 。

安装 PyAudio (以树莓派 Raspberry Pi OS 为例)

运行环境

  • Python 3.9
  • Raspberry Pi OS

安装步骤(使用 pip )

  • 安装 portaudio.dev
$ sudo apt install portaudio.dev
  • 安装依赖库
$ sudo apt install libportaudio0 libportaudio2 libportaudiocpp0 portaudio19-dev
  • 安装 pyaudio
$ sudo pip3 install pyaudio

服务器端

详细代码如下。

import socket
import time
import threading

class Server:

    def __init__(self):
        self.ip = '192.168.8.150'
        while True:
            try:
                self.port = 9808
                self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                self.s.bind((self.ip, self.port))

                self.s2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                self.s2.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
                break
            except:
                print("Couldn't bind to that port")
                
        self.connections = []
        self.accept_connections()

    def accept_connections(self):
        self.s.listen(32) #max suspend queue
        while True:
            c, addr = self.s.accept()
            self.connections.append(c)
            print('Found client at {}'.format(addr))
            threading.Thread(target=self.handle_client, args=(c, addr,)).start()

    def broadcast(self, sock, data):
        for client in self.connections:
            if client != self.s and client != sock:
                try:
                    client.send(data)
                except:
                    pass

    def handle_client(self, c, addr):
        while 1:
            try:
                data = c.recv(512)
                self.broadcast(c, data)
            except socket.error:
                c.close()

server = Server()

服务器端通过主线程运行监听死循环,在客户端建立连接后随即开启新的线程用于接收客户端数据,并在每次接收后转发给客户端。

客户端

详细代码如下。

class Client:
    def __init__(self,ip):
        self.target_ip = ip
        self.target_port = 9808
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.p = pyaudio.PyAudio()
        self.streaming = False
    
    def start_streaming(self):
        self.streaming = True

        while 1:
            try:
                self.s.connect((self.target_ip, self.target_port))
                break
            except:
                print("Couldn't connect to server")
                time.sleep(2)

        chunk_size = 512 # 512
        audio_format = pyaudio.paInt16
        channels = 1
        rate = 20000
        
        self.playing_stream = self.p.open(format=audio_format, channels=channels, rate=rate, output=True,
        frames_per_buffer=chunk_size)
        self.recording_stream = self.p.open(format=audio_format, channels=channels, rate=rate, input=True,
        frames_per_buffer=chunk_size)
        print("Connected to Server")

        # start threads
        receive_thread = threading.Thread(target=self.receive_server_data).start()
        send_thread = threading.Thread(target=self.send_data_to_server).start()
    
    def stop_streaming(self):
        self.streaming = False

        time.sleep(1)

        self.playing_stream.stop_stream()
        self.playing_stream.close()

        self.recording_stream.stop_stream()
        self.recording_stream.close()

        self.p.terminate()

        print("finished clean up")

    def receive_server_data(self):
        print("started reciving data.")
        while self.streaming:
            try:
                data = self.s.recv(512)
                self.playing_stream.write(data)
            except:
                pass
        print("stopped reciving data.")

    def send_data_to_server(self):
        print("started sending data.")
        while self.streaming:
            try:
                data = self.recording_stream.read(512)
                self.s.sendall(data)
            except:
                pass
        print("stopped sending data.")

与服务端不同的是,客户端定义了一个标识符,用于停止交换数据。

使用时,首先创建 Client 对象。

client = Client(address[0])

在需要交换数据时调用 start_streaming() 方法。

client.start_streaming()

在需要停止交换数据时调用 stop_streaming() 方法。

client.stop_streaming()

164 个评论

  1. Hi there! Do you know if they make any plugins to help with
    Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords
    but I’m not seeing very good success. If you know of
    any please share. Appreciate it!

  2. I simply wanted to make a brief remark to appreciate you for some of the
    superb guides you are sharing on this website. My time-consuming internet
    research has finally been honored with reliable facts
    and techniques to go over with my neighbours.
    I ‘d repeat that we site visitors actually are undoubtedly endowed to
    dwell in a fine site with very many outstanding people with insightful things.
    I feel really happy to have come across your entire site and look forward to plenty of more thrilling moments reading here.
    Thank you once more for all the details.

    Feel free to visit my web-site: http://www.meteoritegarden.com

  3. Have you ever thought about publishing an e-book or
    guest authoring on other websites? I have a blog centered on the same ideas
    you discuss and would really like to have you share some stories/information. I know my audience would enjoy your work.
    If you are even remotely interested, feel free to shoot me an e
    mail.

    Feel free to visit my page: size 9 shoes

  4. I would like to consider the chance of thanking you for that professional suggestions I have
    enjoyed going to your site. We are looking forward to the actual commencement of my school research and the general planning would never have been complete without coming over to your website.
    If I might be of any help to others, I might be happy to help through what I have gained from here.

    my web-site: weight loss plateaus

  5. I almost never write remarks, however i did some searching and wound
    up here 使用 Python 实现局域网语音广播 – 迪莫的博客.

    And I do have 2 questions for you if it’s allright. Could it be simply me or does it look as if like some of these responses look like they are
    left by brain dead folks? 😛 And, if you are writing on other social
    sites, I’d like to follow anything fresh you have to post.
    Would you make a list of the complete urls of your social pages
    like your twitter feed, Facebook page or linkedin profile?

    Feel free to visit my webpage – Jeanna

  6. It is the best time to make a few plans for the future and it is time to
    be happy. I have read this submit and if I may I wish
    to suggest you some attention-grabbing issues or advice.
    Maybe you could write subsequent articles referring to this article.
    I desire to learn even more issues about it!

  7. Hey There. I found your weblog the use of msn. This is
    a very well written article. I will make sure to bookmark
    it and come back to read extra of your helpful information. Thanks for the
    post. I’ll definitely return.

  8. Hello there, just turned into alert to your blog thru Google,
    and located that it is truly informative. I’m gonna be careful for brussels.
    I’ll be grateful if you happen to continue this in future.
    Many other people will likely be benefited out of your writing.

    Cheers!

    Feel free to surf to my web blog Edwina

  9. I just wanted to thank you once again for the amazing site you have created
    here. It really is full of ideas for those who are
    seriously interested in this specific subject, specifically this very post.
    You really are all really sweet as well as thoughtful of others and reading your site posts is a great delight to
    me. And that of a generous present! Dan and I really have
    pleasure making use of your guidelines in what we must do next
    week. Our list is a kilometer long and tips is going
    to be put to great use.

    My webpage :: routine skin

  10. Superb blog! Do you have any tips for aspiring writers?
    I’m planning to start my own blog soon but I’m a little
    lost on everything. Would you propose starting with a free platform like WordPress or go for a
    paid option? There are so many choices out there that I’m totally confused ..
    Any ideas? Thanks!

    My web-site :: seeds exist

  11. Hey there! I know this is kinda off topic however , I’d figured I’d ask.
    Would you be interested in exchanging links or maybe guest authoring a blog post or vice-versa?
    My site addresses a lot of the same subjects
    as yours and I believe we could greatly benefit from each other.
    If you’re interested feel free to send me an e-mail.

    I look forward to hearing from you! Terrific blog by the way!

  12. I wish to convey my gratitude for your kindness in support of those
    who absolutely need help with in this concept. Your personal dedication to
    getting the message all through was unbelievably beneficial and have usually made women like me to realize
    their goals. This informative advice indicates a lot to me and even further to my office workers.
    With thanks; from all of us.

    Here is my blog :: http://www.comegnolaw.com

  13. You really make it seem so easy with your presentation but I find this topic to be really something that I think I would never understand.
    It seems too complex and very broad for me. I’m looking forward for your next post, I’ll
    try to get the hang of it!

    Feel free to visit my web page – better sex

  14. I simply wanted to thank you again for this amazing web page you have
    made here. Its full of useful tips for those who are actually interested in this specific subject, specifically this very post.

    Your all absolutely sweet as well as thoughtful of others
    and reading your website posts is a fantastic delight to me.
    And exactly what a generous reward! Dan and I really have excitement making use of
    your guidelines in what we should do in a few weeks.
    Our listing is a distance long and tips will certainly be put to fine use.

    Here is my page … handmade skin care products

  15. An impressive share! I have just forwarded this onto a friend who
    has been conducting a little research on this. And
    he in fact ordered me breakfast due to the fact that I stumbled upon it for him…
    lol. So allow me to reword this…. Thanks for the meal!!
    But yeah, thanks for spending some time to talk about this issue here on your web site.

    Feel free to visit my page – healthy skin

  16. Thank you for your website post. Manley and I have been saving for our new e book on this theme and your
    writing has made us all to save all of our money.
    Your opinions really resolved all our issues. In fact, over what we had acknowledged ahead of the
    time we discovered your great blog. My partner and i no
    longer have doubts plus a troubled mind because you have clearly attended to our
    own needs in this post. Thanks

    Also visit my blog – springwoodslasher.com

  17. Hi there very cool website!! Guy .. Excellent .. Wonderful ..
    I will bookmark your blog and take the feeds additionally…I’m happy
    to search out numerous helpful info here in the put up, we want work out extra techniques in this regard, thank you for sharing.

    Here is my website … gain muscle

  18. First off I want to say excellent blog! I had a quick question which I’d like to ask if you don’t mind.
    I was interested to know how you center yourself and clear your mind prior to writing.
    I’ve had difficulty clearing my mind in getting my thoughts out there.
    I truly do enjoy writing however it just seems like the first
    10 to 15 minutes tend to be lost just trying to figure
    out how to begin. Any ideas or hints? Appreciate it!

  19. Howdy, i read your blog occasionally and i own a similar
    one and i was just wondering if you get a lot of spam comments?
    If so how do you reduce it, any plugin or anything you can advise?

    I get so much lately it’s driving me insane
    so any assistance is very much appreciated.

  20. Hey! I realize this is somewhat off-topic but I had to
    ask. Does operating a well-established website such as yours require a massive amount work?
    I am completely new to blogging but I do write in my
    diary every day. I’d like to start a blog so I can easily share my personal experience
    and views online. Please let me know if you have any ideas or tips for weight loss for
    brand new aspiring bloggers. Appreciate it!

  21. Garrett can see what his father is doing, unconsciously his hands moves to his cock. He strokes the length of his tool with his left hand while he teases the blistering red crown with the fingertips of his right hand. The lightning of his cool fingertips sends sparks through every nerve in his body.

  22. “Damn it, son! Damn it! Damn it, you hit the mirror above the sink!” His father shouts as the bullets of cum shoot forth from his son’s cock and hits the adjacent mirror directly in front of the porcelain bathroom thrown.

  23. Exactly a week after, daddy texted me with a different tone saying, “ get your ass ready tonight cause daddy is coming to your place tonight.” He was usually really sweet and nice, I was shot when I got the message. But automatically I said, “ yes daddy!” I guess I am a slutty whore for him right at the beginning as I knew my place where is always going to be inferior.

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注