ASR_client.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. import argparse
  9. parser = argparse.ArgumentParser()
  10. parser.add_argument("--host",
  11. type=str,
  12. default="localhost",
  13. required=False,
  14. help="host ip, localhost, 0.0.0.0")
  15. parser.add_argument("--port",
  16. type=int,
  17. default=10095,
  18. required=False,
  19. help="grpc server port")
  20. parser.add_argument("--chunk_size",
  21. type=int,
  22. default=300,
  23. help="ms")
  24. args = parser.parse_args()
  25. voices = Queue()
  26. # 其他函数可以通过调用send(data)来发送数据,例如:
  27. async def record():
  28. #print("2")
  29. global voices
  30. FORMAT = pyaudio.paInt16
  31. CHANNELS = 1
  32. RATE = 16000
  33. CHUNK = int(RATE / 1000 * args.chunk_size)
  34. p = pyaudio.PyAudio()
  35. stream = p.open(format=FORMAT,
  36. channels=CHANNELS,
  37. rate=RATE,
  38. input=True,
  39. frames_per_buffer=CHUNK)
  40. while True:
  41. data = stream.read(CHUNK)
  42. voices.put(data)
  43. #print(voices.qsize())
  44. await asyncio.sleep(0.01)
  45. async def ws_send():
  46. global voices
  47. global websocket
  48. print("started to sending data!")
  49. while True:
  50. while not voices.empty():
  51. data = voices.get()
  52. voices.task_done()
  53. try:
  54. await websocket.send(data) # 通过ws对象发送数据
  55. except Exception as e:
  56. print('Exception occurred:', e)
  57. await asyncio.sleep(0.01)
  58. await asyncio.sleep(0.01)
  59. async def message():
  60. global websocket
  61. while True:
  62. try:
  63. print(await websocket.recv())
  64. except Exception as e:
  65. print("Exception:", e)
  66. async def ws_client():
  67. global websocket # 定义一个全局变量ws,用于保存websocket连接对象
  68. # uri = "ws://11.167.134.197:8899"
  69. uri = "ws://{}:{}".format(args.host, args.port)
  70. #ws = await websockets.connect(uri, subprotocols=["binary"]) # 创建一个长连接
  71. async for websocket in websockets.connect(uri, subprotocols=["binary"], ping_interval=None):
  72. task = asyncio.create_task(record()) # 创建一个后台任务录音
  73. task2 = asyncio.create_task(ws_send()) # 创建一个后台任务发送
  74. task3 = asyncio.create_task(message()) # 创建一个后台接收消息的任务
  75. await asyncio.gather(task, task2, task3)
  76. asyncio.get_event_loop().run_until_complete(ws_client()) # 启动协程
  77. asyncio.get_event_loop().run_forever()