Skip to main content

BRTC Python SDK

Python Version License

Baidu Real-Time Communication (BRTC) Python SDK - 基于 aiortc 和信令的实时音视频通信 SDK。

特性

  • 完整的 WebRTC 支持: 基于 aiortc 实现,支持音视频通信、数据通道
  • 多种音视频发送方式: 支持 aiortc 采集和直接发送编码后数据
  • 完整的VideoRoom 支持: 房间管理、用户管理、发布/订阅
  • 数据通道: 支持文本和二进制数据发送/接收
  • 异步设计: 基于 asyncio,高性能非阻塞

安装

pip install baidurtc

快速开始

基础使用示例

import asyncio
from baidurtc import BaiduRtcClient, EventObserver

class MyEventObserver(EventObserver):
    def on_rtc_login_ok(self):
        print("登录成功")
    
    def on_rtc_webrtc_up(self, feed_id: int):
        print(f"WebRTC 连接建立: feed_id={feed_id}")
    
    def on_rtc_feed_coming(self, feed_id: int, name: str):
        print(f"用户加入: {name} (feed_id={feed_id})")
    
    def on_rtc_user_message(self, feed_id: int, msg: str):
        print(f"收到消息 from {feed_id}: {msg}")

async def main():
    # 创建客户端并配置 (Fluent API)
    client = (
        BaiduRtcClient()
        .set_app_id("your-app-id")
        .set_room_name("test-room")
        .set_user_id(12345)
        .set_display_name("User123")
        .set_token("your-token")
        .set_server_url("wss://rtc.exp.bcelive.com/janus")
        .set_audio_codec("opus")
        .set_video_codec("H264")
        .set_has_audio(True)
        .set_has_video(True)
        .set_has_data(True)
    )
    
    # 设置事件观察者
    client.set_event_observer(MyEventObserver())
    
    # 登录并加入房间
    await client.login()
    
    # 等待一段时间
    await asyncio.sleep(60)
    
    # 退出
    await client.logout()

if __name__ == "__main__":
    asyncio.run(main())

音视频发送示例

import asyncio
from baidurtc import BaiduRtcClient

async def send_media():
    client = (
        BaiduRtcClient()
        .set_app_id("your-app-id")
        .set_room_name("test-room")
        .set_user_id(12345)
        .set_display_name("User123")
        .set_token("your-token")
        .set_has_audio(True)
        .set_has_video(True)
    )
    
    await client.login()
    
    # 方式1: 使用 aiortc 自动采集
    audio_devices = await client.media.sources.enumerate_audio_devices()
    video_devices = await client.media.sources.enumerate_video_devices()
    
    await client.media.sources.start_microphone(device_id=audio_devices[0].device_id)
    await client.media.sources.start_camera(device_id=video_devices[0].device_id)
    await client.media.sources.start_sending()
    
    # 方式2: 直接发送编码后的数据
    # 发送 H264 视频帧
    # await client.send_video(h264_frame_data, duration_ms=33)
    
    # 发送 Opus 音频帧
    # await client.send_audio(opus_frame_data, duration_ms=20)
    
    # 发送 PCM 音频 (自动编码)
    # await client.send_audio_pcm(pcm_data, duration_ms=20)
    
    await asyncio.sleep(60)
    await client.logout()

asyncio.run(send_media())

数据通道使用示例

import asyncio
from baidurtc import BaiduRtcClient

async def data_channel_demo():
    client = BaiduRtcClient()
    # ... 配置和登录 ...
    
    # 注册数据接收回调
    def on_data_received(data, label):
        print(f"收到数据 [{label}]: {data}")
    
    client.data_channel.on_data(on_data_received)
    
    # 发送数据
    await client.send_data("Hello, World!")
    await client.send_raw_data(b"Binary data")
    
    # 或通过数据通道管理器发送
    await client.data_channel.send_json({"action": "ping"})
    await client.data_channel.send_message("用户消息", to_user=0)

asyncio.run(data_channel_demo())

架构

┌─────────────────────────────────────────────────────────────┐
│                    BaiduRtcClient                           │
├─────────────────────────────────────────────────────────────┤
│  RoomManager │ UserManager │ MediaManager │ DataChannelMgr  │
├─────────────────────────────────────────────────────────────┤
│            MediaSourceManager │ SignalingManager            │
├─────────────────────────────────────────────────────────────┤
│              WebSocketClient │ BRTCProtocol                 │
├─────────────────────────────────────────────────────────────┤
│                    aiortc (WebRTC)                          │
├─────────────────────────────────────────────────────────────┤
│                           BRTC                              │
└─────────────────────────────────────────────────────────────┘

API 文档

主客户端类

  • login() - 登录到 BRTC 服务器
  • logout() - 退出登录
  • send_video(frame, duration_ms) - 发送视频帧
  • send_audio(frame, duration_ms) - 发送音频帧
  • send_audio_pcm(pcm_data, duration_ms) - 发送 PCM 音频
  • send_data(text) - 发送数据通道文本
  • send_raw_data(bytes) - 发送数据通道二进制数据

配置方法 (Fluent API)

  • set_app_id(app_id) - 设置应用 ID
  • set_room_name(room_name) - 设置房间名称
  • set_user_id(user_id) - 设置用户 ID
  • set_display_name(name) - 设置显示名称
  • set_token(token) - 设置认证 Token
  • set_audio_codec(codec) - 设置音频编解码器
  • set_video_codec(codec) - 设置视频编解码器
  • set_has_audio(enabled) - 启用/禁用音频
  • set_has_video(enabled) - 启用/禁用视频
  • set_has_data(enabled) - 启用/禁用数据通道

观察者接口

  • EventObserver - 事件观察者

    • on_rtc_login_ok() - 登录成功
    • on_rtc_webrtc_up(feed_id) - WebRTC 连接建立
    • on_rtc_feed_coming(feed_id, name) - 用户加入
    • on_rtc_user_message(feed_id, msg) - 收到消息
    • ...
  • MediaObserver - 媒体观察者

    • on_video_frame(feed_id, data, codec) - 收到视频帧
    • on_audio_data(feed_id, data, sample_rate, channels) - 收到音频数据
    • ...

更多示例

查看 sdkdemo/ 目录获取更多使用示例:

  • basic_usage.py - 基础使用
  • media_sending.py - 音视频发送
  • data_channel.py - 数据通道
  • push_demo.py - 推流演示(从本地文件推送音视频)
  • pull_demo.py - 拉流演示(订阅远端流)
  • videocall_demo.py - 视频通话演示

依赖

  • Python 3.8+
  • aiortc >= 1.6.0
  • websockets >= 11.0
  • av >= 10.0.0

协议

BSD-3-Clause License

相关链接

Metadata

Release files for baidurtc 0.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for baidurtc 0.0.1
File Size Uploaded Provenance
baidurtc-0.0.1.tar.gz 38.7 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for baidurtc 0.0.1
File Interpreter ABI Platform
baidurtc-0.0.1-py3-none-any.whl Python 3 none any Details

Total release size: 75.0 kB

Release files / baidurtc-0.0.1.tar.gz

Download URL baidurtc-0.0.1.tar.gz
Size 38.7 kB
Tags Source
SHA-256 checksum
How to use checksums
83303ce28ca87439ac221e0903f0998cfeedf9bee94837c64bfa5d2f867a98de
BLAKE2b-256 checksum
How to use checksums
f28102fd803f17d64df07f88b95d7419fdcfc81e233c271cf62cd097247c0047
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.10.9 {"installer":{"name":"uv","version":"0.10.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / baidurtc-0.0.1-py3-none-any.whl

Download URL baidurtc-0.0.1-py3-none-any.whl
Size 36.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
760c39b51c2478a4f4dd0e15a8844676611bf6d42445c9ca9c98ee57013497ba
BLAKE2b-256 checksum
How to use checksums
3de13c6968b3a9a91f633d9d87f131e80dd7f51be87a6d4af6aaf33a193fd4a9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.10.9 {"installer":{"name":"uv","version":"0.10.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for baidurtc 0.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Release history Release notifications | RSS feed

This release

0.0.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page