白桦的天空

第一次的心动,永远的心痛!
随笔 - 349, 文章 - 15, 评论 - 203, 阅读 - 25万
  首页  :: 新随笔  :: 联系 :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

服务端代码:

#!/bin/env python
# -*- coding: utf-8 -*-
 
import asyncio
import websockets
import time
import threading
import signal
import sys
import pyaudio
import numpy as np
from multiprocessing import Process, Value
import multiprocessing
import ctypes
 
is_exit = False
 
def record(voice_rate):
    global is_exit   
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paInt16,
                    channels=1,
                    rate=16000,
                    input=True,
                    frames_per_buffer=1024)
 
    while not is_exit:
        data = stream.read(1024)
        audio_data = np.fromstring(data, dtype=np.short)
        max_dB = np.max(audio_data)
        voice_rate.value = max_dB
        time.sleep(0.1)
 
 
def sig_handler(signum, frame):
    global is_exit
    is_exit = True
    sys.exit(0)
 
 
async def sendData(websocket, path):
    # rev = await websocket.recv()
    # print(f"client: {rev}")   
    await websocket.send(str(voice_rate.value))
 
if __name__ == "__main__":
    voice_rate = multiprocessing.Manager().Value(ctypes.c_int, 0)
    signal.signal(signal.SIGINT, sig_handler)
    # t = threading.Thread(target=add_variable, args=())
    # t.setDaemon(True)
    # t.start()
 
    p = Process(target=record, args=(voice_rate,))
    p.start()
 
    start_server = websockets.serve(sendData, '127.0.0.1', 8765)
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()

  客户端代码:

复制代码
import asyncio
import websockets
import time


async def getData():
    uri = "ws://127.0.0.1:8765"
    async with websockets.connect(uri) as websocket:
        await websocket.send("rate")
        ret = await websocket.recv()
        print(f"server: {ret}")
        time.sleep(0.1)
        await getData()

asyncio.get_event_loop().run_until_complete(getData())
复制代码

 

相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示