-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrealtime.py
72 lines (48 loc) · 1.38 KB
/
realtime.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import pyaudio
import asyncio
import websockets
import os
import json
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 8000
CHUNK = 8000
audio_queue = asyncio.Queue()
def callback(input_data, frame_count, time_info, status_flags):
audio_queue.put_nowait(input_data)
return (input_data, pyaudio.paContinue)
async def microphone():
audio = pyaudio.PyAudio()
stream = audio.open(
format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
stream_callback=callback
)
stream.start_stream()
while stream.is_active():
await asyncio.sleep(0.1)
stream.stop_stream()
stream.close()
async def process():
async with websockets.connect(
'ws://localhost:8000/ws?sample_rate=8000&language=es',
) as ws:
async def sender(ws): # sends audio to websocket
try:
while True:
data = await audio_queue.get()
await ws.send(data)
except Exception as e:
print('Error while sending: ', + str(e))
raise
async def receiver(ws):
async for msg in ws:
print(msg)
await asyncio.gather(sender(ws), receiver(ws))
async def run():
await asyncio.gather(microphone(), process())
if __name__ == '__main__':
asyncio.run(run())