Stream an audio file.
(args)
| 153 | |
| 154 | |
| 155 | async def run_file(args): |
| 156 | """Stream an audio file.""" |
| 157 | try: |
| 158 | import soundfile as sf |
| 159 | except ImportError: |
| 160 | print("Please install soundfile: pip install soundfile") |
| 161 | sys.exit(1) |
| 162 | |
| 163 | audio, sr = sf.read(args.file) |
| 164 | if sr != SAMPLE_RATE: |
| 165 | try: |
| 166 | import librosa |
| 167 | audio = librosa.resample(audio, orig_sr=sr, target_sr=SAMPLE_RATE) |
| 168 | except ImportError: |
| 169 | print(f"Audio is {sr}Hz, need 16kHz. Install librosa: pip install librosa") |
| 170 | sys.exit(1) |
| 171 | if audio.ndim > 1: |
| 172 | audio = audio[:, 0] |
| 173 | audio = audio.astype(np.float32) |
| 174 | |
| 175 | duration = len(audio) / SAMPLE_RATE |
| 176 | print(f"File: {args.file} ({duration:.1f}s)") |
| 177 | print(f"Connecting to {args.server}...") |
| 178 | |
| 179 | async with websockets.connect(args.server, ping_interval=None) as ws: |
| 180 | await ws.send("START") |
| 181 | await ws.recv() |
| 182 | |
| 183 | if args.hotwords: |
| 184 | await ws.send(f"HOTWORDS:{args.hotwords}") |
| 185 | await ws.recv() |
| 186 | |
| 187 | int16 = (audio * 32768).clip(-32768, 32767).astype(np.int16) |
| 188 | |
| 189 | chunk_size = CHUNK_SAMPLES |
| 190 | total_chunks = (len(int16) + chunk_size - 1) // chunk_size |
| 191 | |
| 192 | async def send_audio(): |
| 193 | for i in range(0, len(int16), chunk_size): |
| 194 | chunk = int16[i:i+chunk_size] |
| 195 | await ws.send(chunk.tobytes()) |
| 196 | await asyncio.sleep(CHUNK_DURATION_MS / 1000 * 0.5) |
| 197 | await ws.send("STOP") |
| 198 | |
| 199 | async def recv_results(): |
| 200 | async for msg in ws: |
| 201 | data = json.loads(msg) |
| 202 | if "sentences" in data: |
| 203 | print_result(data, show_spk=args.spk) |
| 204 | if data.get("is_final") or data.get("event") == "stopped": |
| 205 | break |
| 206 | |
| 207 | await asyncio.gather(send_audio(), recv_results()) |
| 208 | |
| 209 | |
| 210 | def main(): |
no test coverage detected