Stream from microphone.
(args)
| 87 | |
| 88 | |
| 89 | async def run_mic(args): |
| 90 | """Stream from microphone.""" |
| 91 | try: |
| 92 | import sounddevice as sd |
| 93 | except ImportError: |
| 94 | print("Please install sounddevice: pip install sounddevice") |
| 95 | sys.exit(1) |
| 96 | |
| 97 | print(f"Connecting to {args.server}...") |
| 98 | async with websockets.connect(args.server, ping_interval=None) as ws: |
| 99 | await ws.send("START") |
| 100 | resp = await ws.recv() |
| 101 | event = json.loads(resp) |
| 102 | if event.get("event") != "started": |
| 103 | print(f"Unexpected response: {resp}") |
| 104 | return |
| 105 | |
| 106 | if args.hotwords: |
| 107 | await ws.send(f"HOTWORDS:{args.hotwords}") |
| 108 | await ws.recv() |
| 109 | |
| 110 | print("Recording... Press Ctrl+C to stop\n") |
| 111 | |
| 112 | audio_queue = asyncio.Queue() |
| 113 | |
| 114 | def audio_callback(indata, frames, time_info, status): |
| 115 | audio_queue.put_nowait(indata.copy()) |
| 116 | |
| 117 | stream = sd.InputStream( |
| 118 | samplerate=SAMPLE_RATE, channels=1, dtype='int16', |
| 119 | blocksize=CHUNK_SAMPLES, callback=audio_callback, |
| 120 | ) |
| 121 | |
| 122 | async def send_audio(): |
| 123 | with stream: |
| 124 | while True: |
| 125 | chunk = await audio_queue.get() |
| 126 | await ws.send(chunk.tobytes()) |
| 127 | |
| 128 | async def recv_results(): |
| 129 | async for msg in ws: |
| 130 | data = json.loads(msg) |
| 131 | if "sentences" in data: |
| 132 | print_result(data, show_spk=args.spk) |
| 133 | if data.get("is_final") or data.get("event") == "stopped": |
| 134 | break |
| 135 | |
| 136 | send_task = asyncio.create_task(send_audio()) |
| 137 | recv_task = asyncio.create_task(recv_results()) |
| 138 | |
| 139 | try: |
| 140 | await asyncio.gather(send_task, recv_task) |
| 141 | except (KeyboardInterrupt, asyncio.CancelledError): |
| 142 | pass |
| 143 | finally: |
| 144 | send_task.cancel() |
| 145 | if ws.open: |
| 146 | await ws.send("STOP") |
no test coverage detected