ASR_client.py 2.8 KB

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