-
Notifications
You must be signed in to change notification settings - Fork 114
Expand file tree
/
Copy pathsubscriber.py
More file actions
66 lines (51 loc) · 1.73 KB
/
subscriber.py
File metadata and controls
66 lines (51 loc) · 1.73 KB
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
import os
import logging
import asyncio
from signal import SIGINT, SIGTERM
from livekit import rtc
# Set the following environment variables with your own values
TOKEN = os.environ.get("LIVEKIT_TOKEN")
URL = os.environ.get("LIVEKIT_URL")
async def subscribe(track: rtc.RemoteDataTrack):
logging.info(
"Subscribing to '%s' published by '%s'",
track.info.name,
track.publisher_identity,
)
subscription = await track.subscribe()
async for frame in subscription:
logging.info("Received frame (%d bytes)", len(frame.payload))
latency = frame.duration_since_timestamp()
if latency is not None:
logging.info("Latency: %.3f s", latency)
async def main(room: rtc.Room):
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
active_tasks = []
@room.on("data_track_published")
def on_data_track_published(track: rtc.RemoteDataTrack):
task = asyncio.create_task(subscribe(track))
active_tasks.append(task)
task.add_done_callback(lambda _: active_tasks.remove(task))
await room.connect(URL, TOKEN)
logger.info("connected to room %s", room.name)
if __name__ == "__main__":
logging.basicConfig(
level=logging.INFO,
handlers=[
logging.FileHandler("subscriber.log"),
logging.StreamHandler(),
],
)
loop = asyncio.get_event_loop()
room = rtc.Room(loop=loop)
async def cleanup():
await room.disconnect()
loop.stop()
asyncio.ensure_future(main(room))
for signal in [SIGINT, SIGTERM]:
loop.add_signal_handler(signal, lambda: asyncio.ensure_future(cleanup()))
try:
loop.run_forever()
finally:
loop.close()