服务端代码:
#!/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())
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库