ASR_client.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import pyaudio
  2. # import websocket #区别服务端这里是 websocket-client库
  3. import time
  4. import websockets
  5. import asyncio
  6. from queue import Queue
  7. # import threading
  8. voices = Queue()
  9. async def hello():
  10. global ws # 定义一个全局变量ws,用于保存websocket连接对象
  11. uri = "ws://localhost:8899"
  12. ws = await websockets.connect(uri, subprotocols=["binary"]) # 创建一个长连接
  13. ws.max_size = 1024 * 1024 * 20
  14. print("connected ws server")
  15. async def send(data):
  16. global ws # 引用全局变量ws
  17. try:
  18. await ws.send(data) # 通过ws对象发送数据
  19. except Exception as e:
  20. print('Exception occurred:', e)
  21. asyncio.get_event_loop().run_until_complete(hello()) # 启动协程
  22. # 其他函数可以通过调用send(data)来发送数据,例如:
  23. async def test():
  24. #print("2")
  25. global voices
  26. FORMAT = pyaudio.paInt16
  27. CHANNELS = 1
  28. RATE = 16000
  29. CHUNK = int(RATE / 1000 * 300)
  30. p = pyaudio.PyAudio()
  31. stream = p.open(format=FORMAT,
  32. channels=CHANNELS,
  33. rate=RATE,
  34. input=True,
  35. frames_per_buffer=CHUNK)
  36. while True:
  37. data = stream.read(CHUNK)
  38. voices.put(data)
  39. #print(voices.qsize())
  40. await asyncio.sleep(0.01)
  41. async def ws_send():
  42. global voices
  43. print("started to sending data!")
  44. while True:
  45. while not voices.empty():
  46. data = voices.get()
  47. voices.task_done()
  48. await send(data)
  49. await asyncio.sleep(0.01)
  50. await asyncio.sleep(0.01)
  51. async def main():
  52. task = asyncio.create_task(test()) # 创建一个后台任务
  53. task2 = asyncio.create_task(ws_send()) # 创建一个后台任务
  54. await asyncio.gather(task, task2)
  55. asyncio.run(main())