aiortc

[TOC]

aiortc

aiortc是 WebRTC 和 ORTC 的Python异步实现。

install

1
2
3
apt install libavdevice-dev libavfilter-dev libopus-dev libvpx-dev pkg-config
# ffmpeg >= 3.2
pip install aiortc

example

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
from aiortc import RTCPeerConnection, RTCSessionDescription
from aiortc import VideoStreamTrack

async def offer(paramse):
# 解析 offer
request_offer = RTCSessionDescription(
sdp=params['sdp'],
type=params['type'])

# 创建一个连接class
pc = RTCPeerConnection()
pcs.add(pc)

# 监听数据通道
@pc.on("datachannel")
def on_datachannel(channel):

# 监听接收数据
@channel.on("message")
def on_message(message):
message_recieve = json.loads(message)
print("message_recieve:{message_recieve}")

# 监听断开连接
@pc.on('iceconnectionstatechange')
async def on_iceconnectionstatechange():
print(f'ICE connection state is {pc.iceConnectionState}')
if pc.iceConnectionState == 'failed':
await pc.close()
pcs.discard(pc)

@pc.on('track')
def on_track(track):
print('Track %s received' % track.kind)
if track.kind == 'audio':
# 接收语音数据
frame = await audio_track.recv()
pass
elif track.kind == 'video':
local_video = VideoTransformTrack(track)
pc.addTrack(local_video)

@track.on('ended')
async def on_ended():
print('Track %s ended' % track.kind)

# 设置 请求端 连接信息: request_offer
await pc.setRemoteDescription(request_offer)

# 设置 响应端 连接信息: answer
answer = await pc.createAnswer()
await pc.setLocalDescription(answer)
# 将 响应端 信息返回给 请求端: offer_result
offer_result = json.dumps({'sdp': pc.localDescription.sdp, 'type': pc.localDescription.type})
return offer_result

更多例子: https://github.com/aiortc/aiortc/tree/master/examples